2015-12-23 12 views
5

Otrzymuję ten błąd na poniższym bloku kodu.Błąd TS2339: Właściwość "endsWith" nie istnieje na typie "ciąg"

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 odkryli również link, który pokazuje, że istnieje funkcja endsWith(...).

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

Czy tęsknię trochę .d.ts plik czy co?

Odpowiedz

12

endsWith jest ES6 function więc trzeba kierować ES6 w ustawieniach kompilatora maszynopis lub można dodać interfejs do niego:

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

[Playground]

+0

Definicje funkcji ES6 znajdują się tutaj https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es6.dts na przyszłość. –

+0

W końcu zastąpiłem coś innego za pomocą 'indexOf', ponieważ miałem problemy z linerem. – ipinak

0

tutaj: użyłem kodu VS jako IDE
Problem:

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

spowoduje:

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

Rozwiązanie:
powinien zawierać następujący plik tsconfig.json w projekcie:

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

Następnie użyłem tsc (bez nazwy pliku), więc transpiler użyje tsconfig.json do trans-kompilacji wszystkich plików skryptowych typu hostowanych w katalogach do plików js.

0

Podczas kompilowania kodu maszynowego, wskaż cel na ES6.

tsc --target ES6 "filename" 
Powiązane problemy