2015-03-01 12 views
6

Probabilmente mi manca qualcosa di stupido qui. Ho pensato che il tipo tupla [string, number] era più o meno equivalente al tipo (string | number)[] array-of-unione, e che il seguente era quindi legale:Tipo tupla vs. tipo matrice-unione

function lengths (xs: string[]): [string, number][] { 
    return xs.map((x: string) => [x, x.length]) 
} 

Tuttavia TSC 1.4 lamenta:

Config.ts(127,11): error TS2322: Type '(string | number)[][]' is not assignable to type '[string, number][]'. 
    Type '(string | number)[]' is not assignable to type '[string, number]'. 
    Property '0' is missing in type '(string | number)[]'. 

Che cosa sto facendo sbagliato?

risposta

5

Questa risposta è per gentile concessione di Daniel Rosenwasser. Puoi ottenere il comportamento che desideri dando al tuo lambda un tipo di ritorno.

function lengths(xs: string[]): [string, number][] { 
    return xs.map((x): [string, number] => [x, x.length]); 
} 

Altre informazioni here.

Problemi correlati