首页 > 解决方案 > Typescript String.format 不存在

问题描述

我有一个字符串 const 我必须替换两个单词,如下所示:

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'

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

 MY_STRING.format(page, id)

我怎样才能做到这一点?

标签: typescriptstring-interpolation

解决方案


修改原生原型(String. 由于 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 具有提供基本相同功能的模板文字:

const myTemplate = (page: number, id: number) => `page=${page}&id=${id}`;
const formattedWithTemplate = myTemplate(123, 456);
console.log(formattedWithTemplate); // page=123&id=456

如果您打算修改的原型String并且之前的警告并没有阻止您,那么您可以使用全局扩充模块扩充方法来允许 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

但希望您会使用其他解决方案之一。


好的,希望有帮助;祝你好运!

游乐场链接


推荐阅读