gpt4 book ai didi

Typescript String.format 不存在

转载 作者:行者123 更新时间:2023-12-02 00:08:03 26 4
gpt4 key购买 nike

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

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)

我怎样才能做到这一点?

最佳答案

修改像 String 这样的原生原型(prototype)被认为是 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 的原型(prototype)并且之前的警告没有阻止您,那么您可以使用 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

关于Typescript String.format 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59934393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com