Búsqueda de sitios web

typescript - Diferencia entre string[] y [string]


Considera el siguiente ejemplo de Typescript. La primera línea resulta en un error 'tipo undefined[] no es asignable al tipo [string]'. Las dos últimas líneas sí se compilan.

let givesAnError: [string] = [];
let isOK: string[] = [];
let isAlsoOK: [string] = ["foo"];

¿Cómo tienes que interpretar la definición de tipo [string] en Typescript?

Respuesta #1

El primero (givesAnError) y el último (isAlsoOK) son tuplas, y el segundo (isOK) es un arreglo.

Con los arreglos, todos tus elementos son del mismo tipo:

let a: string[];
let b: boolean[];
let c: any[];

Pero con las tuplas puedes tener diferentes tipos (y una longitud fija):

let a: [string, boolean, number];
let b: [any, any, string];

Entonces :

a = ["str1", true, 4]; // fine
b = [true, 3, "str"]; // fine

Pero :

a = [4, true, 3]; // not fine as the first element is not a string
b = [true, 3]; // not fine because b has only two elements instead of 3

Es importante entender que la salida de JavaScript siempre utilizará arreglos, ya que no existe tal cosa como tupla en JS.
Pero para el tiempo de compilación es útil.

Respuesta #2

Directo al grano

string[] // n-length array, must only contain strings

[string] // must be 1-length array, first element must be a string

Artículos relacionados