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

Mic*_*ber 22 javascript typescript

我已经看到了关于字符串数组而不是实际字符串提到的这个错误.我有一个带有该行的TypeScript文件

if (!bus.lineInfo.PublishedLineName.includes(input)) {
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误

TS2339: Property 'includes' does not exist on type 'string'.
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

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

hgi*_*sac 36

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

{
  "compilerOptions": {
    ...
    "lib": [
       "dom",
       "es7"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您不再需要支持ES5,请将构建目标更改为es2016

{
  "compilerOptions": {
    ...
    "target" "es2016"
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这在带有Typescript 3.2.2的VSCode中不起作用.最近几个月发生了什么变化? (5认同)
  • dom支持前端接口(DOM,事件...)。某些库同时用于前端和后端,在编译时会警告语法错误。如果您开发后端,并且在编译时没有错误,则可以将其删除 (2认同)