考虑bad practice来修改诸如String
之类的原生原型。由于JavaScript中没有针对字符串的标准format()
方法,因此添加自己的方法可能会导致在同一运行时中运行的任何代码中出现意外行为。您的实现甚至会首先检查现有的String.prototype.format
,这意味着如果有人先采用其他实现到达那里,那么 you 可能是行为异常的人。
仅使用stringFormat
函数就可以了,这绝对没有错,就像这样:
function stringFormat(template: string,...args: any[]) {
return template.replace(/{(\d+)}/g,function (match,number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
const myString: string = 'page={0}&id={1}';
const formattedWithFormat = stringFormat(myString,123,456);
console.log(formattedWithFormat); // page=123&id=456
JavaScript还具有template literals,它们提供了基本相同的功能:
const myTemplate = (page: number,id: number) => `page=${page}&id=${id}`;
const formattedWithTemplate = myTemplate(123,456);
console.log(formattedWithTemplate); // page=123&id=456
如果您打算修改String
的原型,而以前的警告并没有阻止您,那么您可以使用global augmentation或module augmentation方法允许TypeScript识别您希望string
值具有format()
方法:
/* ? here be dragons ? */
interface String {
format(...args: any[]): string;
}
String.prototype.format = function (...args) { return stringFormat(String(this),...args) };
console.log(myString.format(123,789)); // page=123&id=789
但希望您将使用其他解决方案之一。
好的,希望能有所帮助;祝你好运!
Playground link
,
您可以从基础库中扩展字符串的声明:
RTCPeerConnection()
Playground Link
注意:如果不需要模块declare global {
interface String {
format(...args: []): string
}
}
,则只需将declare global
移到顶层(Playground Link)
本文链接:https://www.f2er.com/2704369.html