gpt4 book ai didi

javascript - TypeScript:标记的模板文字显示错误

转载 作者:数据小太阳 更新时间:2023-10-29 04:09:46 24 4
gpt4 key购买 nike

我正在尝试使用 tagged template literal带有 typescript 的 ES5,但似乎 typescript 没有完全支持它。我有以下代码。

class TemplateLiterals { 
age: number = 24;
name: 'Luke Skywalker'
private tag(strings: string[], personExp, ageExp) :string{
var str0 = strings[0]; // "that "
var str1 = strings[1]; // " is a "
var ageStr;
if (ageExp > 99) {
ageStr = 'centenarian';
} else {
ageStr = 'youngster';
}
return str0 + personExp + str1 + ageStr;
}
toString() {
return this.tag `that ${ this.name } is a ${ this.age }`;
}
}

toString 方法中,typescript 显示以下错误。

Argument of type 'TemplateStringsArray' is not assignable to parameter of type 'string[]'.
Property 'push' is missing in type 'TemplateStringsArray'.

我不知道为什么它向我显示此错误。根据 mozilla 的文档“标记函数的第一个参数包含一个字符串值数组。”所以它应该接受字符串数组。但实际期望是 TemplateStringsArray。不确定如何以及何时定义 interface TemplateSringsArray。目前我正在使用 TemplateSringsArray 类型来避免这个错误。谁能解释一下发生了什么。谢谢。这是 playground .

最佳答案

经过更多探索,我终于在 change log 中找到了解释。 .希望它能帮助别人。它说

ES2015 tagged templates always pass their tag an immutable array-like object that has a property called raw (which is also immutable). TypeScript names this object the TemplateStringsArray.

Conveniently, TemplateStringsArray was assignable to an Array, so it's possible users took advantage of this to use a shorter type for their tag parameters:

function myTemplateTag(strs: string[]) {
// ...
}

However, in TypeScript 2.0, the language now supports the readonly modifier and can express that these objects are immutable. As a result, TemplateStringsArray has also been made immutable, and is no longer assignable to string[].

建议:

使用 TemplateStringsArray明确地(或使用 ReadonlyArray<string> )。

关于javascript - TypeScript:标记的模板文字显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42501856/

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