错误TS2339:类型'string'上不存在属性'endsWith'

时间:2015-12-23 08:59:21

标签: angularjs typescript ecmascript-6 lodash

我在下面的代码块中收到此错误。

error TS2339: Property 'endsWith' does not exist on type 'string'

let myList = angular.element(elem).attr("href").split("/");
let last = _.last<string>(myList);
if (last.endsWith("something")) {
   return last;
}

我还发现此链接显示有一个函数endsWith(...)

http://definitelytyped.org/docs/typescript-services--typescriptServices/classes/typescript.stringutilities.html

我是否遗漏了一些.d.ts文件或什么?

5 个答案:

答案 0 :(得分:14)

<div data-sly-use.search="Search"> <ul data-sly-list.result="${search.listResults}"> <li>${result.title}</li> </ul> </div> ES6 function,因此您需要在TypeScript编译器设置中定位endsWith,或者您可以为其添加界面:

ES6

[Playground]

答案 1 :(得分:11)

在编写打字稿代码时,请将目标指向ES6。

tsc --target ES6 "filename"

答案 2 :(得分:3)

这里:我使用VS代码作为IDE
问题是:

let fName:String = "Yokey";
console.log(fName.anchor("url"));

会导致:

PS C:\MYahya\OS_DEV\typescript_lrn\1> tsc main.ts
main.ts(2,19): error TS2339: Property 'anchor' does not exist on type 'String'.

解决方案:
我应该在项目中包含以下tsconfig.json文件:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": true,
        "strictNullChecks": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "baseUrl": "../types",
        "typeRoots": [
            "../types"
        ],
        "types": [],
        "forceConsistentCasingInFileNames": true,
    }
}

然后我使用tsc(没有文件名),因此转换器将使用tsconfig.json将目录中托管的所有类型脚本文件反编译为js个文件。

答案 3 :(得分:0)

如果您使用像WebStorm这样的intelliJ IDE,请单击项目文件在左侧的区域,然后搜索tsconfig.json。在该文件中,您将看到es设置为较旧的版本,只需将“ target”:“ es3”更改为最新版本,例如“ target”:“ es2018”

答案 4 :(得分:0)

  • 使用以下命令在TypeScript编译器设置中定位ES6(Java脚本版本):

     Command:   tsc --target ES6 main.ts
    
  • 如果要同时转译并运行文件,请使用 下面的命令:

     Command : tsc --target ES6 main.ts | node main.js
    
相关问题