2015-12-29 14 views
10

Sto avendo un problema con la mia funzione:dattiloscritto: Indice firma del tipo di oggetto ha implicitamente un 'qualsiasi' tipo

copyObject<T> (object:T):T { 
     var objectCopy = <T>{}; 
     for (var key in object) { 
      if (object.hasOwnProperty(key)) { 
       objectCopy[key] = object[key]; 
      } 
     } 
     return objectCopy; 
    } 

E ho seguente errore:

Index signature of object type implicitly has an 'any' type. 

Come posso risolvere il problema vero?

+0

Penso che sia a causa della 'var key in object' e dell'uso di' key' in seguito. Puoi provare a eseguire la compilation con 'noImplicitAny = false' per confermare? – FlorianTopf

risposta

12
class test<T> { 
    copyObject<T> (object:T):T { 
     var objectCopy = <T>{}; 
     for (var key in object) { 
      if (object.hasOwnProperty(key)) { 
       objectCopy[key] = object[key]; 
      } 
     } 
     return objectCopy; 
    } 
} 

Se eseguo il codice come segue

c:\Work\TypeScript>tsc hello.ts 

funziona OK. Tuttavia, il codice seguente:

c:\Work\TypeScript>tsc --noImplicitAny hello.ts 

getta

hello.ts(6,17): error TS7017: Index signature of object type implicitly has an 'any' type. 
hello.ts(6,35): error TS7017: Index signature of object type implicitly has an 'any' type. 

Quindi, se si disattiva noImplicitAny bandiera, funzionerà.

Sembra che ci sia un'altra opzione anche perché tsc supporta il flag seguente:

--suppressImplicitAnyIndexErrors Suppress noImplicitAny errors for indexing objects lacking index signatures. 

Questo funziona anche per me:

tsc --noImplicitAny --suppressImplicitAnyIndexErrors hello.ts 

Aggiornamento:

class test<T> { 
    copyObject<T> (object:T):T { 
     let objectCopy:any = <T>{}; 
     let objectSource:any = object; 
     for (var key in objectSource) { 
      if (objectSource.hasOwnProperty(key)) { 
       objectCopy[key] = objectSource[key]; 
      } 
     } 
     return objectCopy; 
    } 
} 

Questo codice funziona senza modificare alcuna compilation er bandiere.

+1

Funziona alla grande! Grazie! – uksz

+4

Ciao Martin, ottima risposta alla domanda, mi stavo chiedendo se tu (o qualcun altro) sai perché questo funziona, o perché dobbiamo definire le variabili objectCopy e objectSource locali? –

Problemi correlati