TS2339:“字符串”类型上不存在属性“包含”
由我怕爱的太早我们不能终老 提交于2019-12-04 22:26:19
我已经看到关于字符串数组而不是实际字符串的这个错误。我有一个带有该行的 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被声明为 a string,并且String.prototype.includes() 根据 MDN 是一个函数,那么为什么 TypeScript 编译器会抱怨缺少属性/方法呢?

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

{
  "compilerOptions": {
    ...
    "lib": [
       "dom",
       "es7"
    ]
  }
}
或者如果您不再想支持 ES5,请将构建目标更改为 es2016

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

来源:https://stackoverflow.com/questions/51811239/ts2339-property-includes-does-not-exist-on-type-string

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐