【问题标题】:error TS2339: Property 'endsWith' does not exist on type 'string'错误 TS2339:“字符串”类型上不存在属性“endsWith”
【发布时间】:2016-03-29 16:00:15
【问题描述】:

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

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 文件还是什么?

【问题讨论】:

    标签: angularjs typescript ecmascript-6 lodash


    【解决方案1】:
    • 使用以下命令在您的 TypeScript 编译器设置中定位 ES6(Java Script 版本):

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

       Command : tsc --target ES6 main.ts | node main.js
      

    【讨论】:

      【解决方案2】:

      如果您使用的是诸如 WebStorm 之类的 IntelliJ IDE,请单击左侧项目文件所在的区域,然后搜索 tsconfig.json。在该文件中,您将看到您的 es 设置为旧版本,只需将 "target": "es3" 更改为最新版本,如 "target": "es2018"

      【讨论】:

        【解决方案3】:

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

        tsc --target ES6 "filename"
        

        【讨论】:

        • 最好的直接方式:D
        • @SharifYazdian - 为什么这是“最佳”方式?这可能很简单,但将目标更改为 ES6 意味着浏览器版本兼容的潜在问题。
        • 或者,如果您需要重复执行此操作,请创建 tsconfig.json 并添加:{ "compilerOptions": {"target":"es6"} }
        • 猜这不是个好主意。当用户需要选择“es5”时,我们不能坚持选择“es6”
        【解决方案4】:

        这里:我使用 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 文件。

        【讨论】:

          【解决方案5】:

          endsWith 是一个 ES6 function,因此您需要在 TypeScript 编译器设置中定位 ES6,或者您可以为其添加接口:

          interface String {    
              endsWith(searchString: string, endPosition?: number): boolean;
          };
          

          [Playground]

          【讨论】:

          猜你喜欢
          • 2018-08-27
          • 2019-08-05
          • 1970-01-01
          • 2019-01-21
          • 2016-08-13
          • 2017-12-20
          • 2016-11-14
          • 2017-10-24
          • 2021-08-10
          相关资源
          最近更新 更多