TS2339:类型“字符串”上不存在属性“包含”

时间:2018-08-12 17:33:00

标签: javascript typescript

我已经看到有关字符串数组但没有实际字符串提及的错误。我有一行的TypeScript文件

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被声明为stringString.prototype.includes() is a function according to MDN,那么为什么TypeScript编译器会抱怨缺少属性/方法?

2 个答案:

答案 0 :(得分:17)

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

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

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

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

答案 1 :(得分:1)

es2016.array.include添加到compilerOptions.lib