2015-12-23 21 views
5

Viene visualizzato questo errore nel blocco di codice riportato di seguito.TS2339: La proprietà 'endsWith' non esiste sul tipo 'stringa'

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

Ho anche scoperto questo link che dimostra che c'è una funzione endsWith(...).

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

mi manca un po 'di .d.ts file o che cosa?

risposta

12

endsWith è un ES6 function quindi è necessario indirizzare ES6 nelle impostazioni del compilatore macchina o è possibile aggiungere un'interfaccia per esso:

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

[Playground]

+0

ES6 definizioni di funzioni si trovano qui https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es6.d.ts per riferimenti futuri. –

+0

Alla fine ho sostituito con qualcos'altro usando 'indexOf', dato che ho avuto problemi con il linter. – ipinak

0

Ecco: ho usato il codice VS come un IDE
Edizione:

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

si tradurrà 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'. 

Soluzione:
devo includere il tsconfig.json file di seguito nel progetto:

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

Poi ho usato tsc (senza il nome del file) in modo che il transpiler utilizzasse lo tsconfig.json per transcompilare tutti i file di script di tipo ospitati nelle directory ai file js.

0

Durante la compilazione del codice dattiloscritto, puntare il bersaglio su ES6.

tsc --target ES6 "filename" 
Problemi correlati