打字稿String.format不存在

我有一个字符串常量,必须替换两个单词,像这样:

public static readonly MY_STRING: string = 'page={0}&id={1}';

0和1必须用其他字符串替换。我已经以不同的答案阅读过有关String.format的文章,他们建议提供这样的实现:

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g,function(match,number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

但是当我做String.format时,它会告诉我

Property 'format' does not exist on type 'String'

在这种情况下使用字符串插值/替换的正确方法是什么?使用format我会做这样的事情:

 MY_STRING.format(page,id)

我该如何实现?

dingweiqiang 回答:打字稿String.format不存在

考虑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 augmentationmodule 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

大家都在问