TS2339:类型 'string' 上不存在属性'includes'



我已经看到这个错误提到字符串数组而不是实际字符串。我有一个打字稿文件,上面有一行

if (!bus.lineInfo.PublishedLineName.includes(input)) {

这给了我一个错误

TS2339: Property 'includes' does not exist on type 'string'.

bus是实现bus接口的变量:

interface bus {
"lineInfo": {
"PublishedLineName": string,
"DestinationName": string, // The headsign of the bus
"Color": string,
"TextColor": boolean | string // false if this is "FFFFFF", otherwise it's the color
},
"warnings": boolean | busWarnings
"marker"?: google.maps.Marker,
"result"?: JQuery // The search result that appears in the sidebar
}

lineInfo.PublishedLineName被声明为string,而String.prototype.includes()是MDN的函数,那么为什么TypeScript编译器会抱怨缺少属性/方法呢?

您应该在 tsconfig.json 中添加 es2016 或 es7libcomplierOptions。默认 TypeScript 不支持某些 es6 polyfill 函数

{
"compilerOptions": {
...
"lib": [
"dom",
"es7"
]
}
}

或者,如果您不再希望再支持 ES5,请将构建目标更改为 es2016

{
"compilerOptions": {
...
"target" "es2016"
}
}

es2016.array.include添加到compilerOptions.lib

最新更新