打字稿 String.format 不存在

Typescript String.format does not exist

我有一个字符串常量,我必须在其中替换两个单词,如下所示:

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'

在这种情况下,使用 String interpolation/substitution 的正确方法是什么?使用格式我会做这样的事情:

 MY_STRING.format(page, id)

我怎样才能做到这一点?

您可以扩充基础库中的字符串声明:

declare global {
    interface String {
        format(...args: []): string
    }
}

Playground Link

注意:如果不在模块中,则不需要 declare global,您可以将 interface String {...} 移动到顶层 (Playground Link)

String这样修改原生原型被认为是bad practice。由于 JavaScript 中的字符串没有标准或商定的 format() 方法,添加您自己的方法可能会导致在同一运行时运行的任何代码出现意外行为。您的实现甚至会首先检查现有的 String.prototype.format,这意味着如果有人首先使用不同的实现到达那里,那么 可能是具有意外行为的人。

使用一个 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 or 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