Error TS2339: Property 'endsWith' does not exist in type 'string'

I get this error on the code block below.

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; } 

I also found this link, which shows that there exists a endsWith(...) function.

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

Skip any .d.ts file or what?

+6
source share
4 answers

endsWith is an ES6 function , so you need to target ES6 in your TypeScript compiler settings or you can add an interface for it:

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

[ Playground ]

+14
source

When compiling your typescript code, specify the target on ES6.

 tsc --target ES6 "filename" 
+10
source

Here: I used VS code as an IDE
The problem was:

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

will result in:

 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'. 

Decision:
I have to include the following tsconfig.json file in the project:

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

Then I used tsc (without a file name), so the transpiler will use tsconfig.json to transcribe all types of script files located in directories into js files.

+2
source

If you are using an IntelliJ IDE, such as WebStorm, click on the area where your project files are located, then find tsconfig.json. In this file you will see that your es is installed on an older version, just change "target": "es3" to the last one, for example, "target": "es2018"

0
source

Source: https://habr.com/ru/post/1239016/


All Articles