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

28

我曾经看到过关于字符串数组的此错误提及,但没有涉及实际字符串。我有一个包含以下行的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被声明为string类型,String.prototype.includes()是MDN中的一个函数,那么为什么TypeScript编译器会抱怨缺少属性/方法?


包括是什么或您认为它是什么? - rmlan
1
我认为这是一个字符串方法;我已经更新了我的帖子,以反映这一点,并附上了一个链接。 - Michael Kolber
2
你的 tsconfig.json 中的 "target" 和 "lib" 设置是什么?String.includes 是 ES6 中的一个方法。 - Matt McCutchen
@MattMcCutchen "target" 设定为 es5。我没有设置 "lib" 选项。将 "lib" 设为 "es2015" 可以解决字符串错误,但会在我从 DefinitelyTyped 中获得的 jQuery d.ts 文件中引发一些错误。 - Michael Kolber
2个回答

46

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

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

或者将构建目标更改为es2016,如果你不再想支持ES5

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

1
太好了!您能否解释一下“dom”是做什么的/包括哪些支持? - Michael Kolber
2
DOM 支持前端接口(DOM,事件...)。某些库同时用于前端和后端,在编译时会提示语法错误。如果您正在开发后端,并且编译时没有错误,则可以将其删除。 - hgiasac
9
在VSCode中使用Typescript 3.2.2时,这无法正常工作。最近几个月发生了什么变化吗? - Lars Nyström
1
我也遇到了同样的问题。你在这方面有找到什么解决方法吗,@LarsNyström? - Tushar Shukla
不,我感到有些力不从心,所以我决定现在远离TS。 - Lars Nyström
我有同样的问题。 - LiHao

3
es2016.array.include添加到compilerOptions.lib

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接