Búsqueda de sitios web

typescript - ¿Cuál es la diferencia entre string[] y una tupla de strings de longitud no fija?


import {Equal} from '@type-challenges/utils';
type StringTuple = [string, ...string[]]; // Tuples also support rest elements
let d: StringTuple = ['a', 'b', 'c'];
let e: StringTuple = ['a', 'b', 'c', 'd', 'e'];
type R = Equal<StringTuple, string[]>; // false

¿Cuál es la diferencia entre StringTuple y string[]? Ambos son arreglos de cadenas de longitud no fija, pero no son iguales.

ACTUALIZACIÓN :

Gracias a @Kelvin Schoofs. Lo entendí:

¡Después de eliminar el string inicial, StringTuple es igual a string[]!

import {Equal} from '@type-challenges/utils';
type StringTuple = [...string[]]; // Tuples also support rest elements
let d: StringTuple = []; // OK!
let e: StringTuple = ['a', 'b', 'c', 'd', 'e'];
type R = Equal<StringTuple, string[]>; // true!

Respuesta #1

Tu StringTuple se define como empezando con un string. No puedes, por ejemplo, asignar un arreglo vacío (¡o incluso string[]!) a una variable StringTuple:

type StringTuple = [string, ...string[]]; // Tuples also support rest elements
let d: StringTuple = ['a', 'b', 'c'];
let e: StringTuple = ['a', 'b', 'c', 'd', 'e'];
let error: StringTuple = [];
// ^ Type '[]' is not assignable to type 'StringTuple'.
//  Source has 0 element(s) but target requires 1.ts(2322)
let error2: StringTuple = (['a', 'b'] as string[]);
// ^ Type 'string[]' is not assignable to type 'StringTuple'.
//  Source provides no match for required element at position 0 in target.ts(2322)

Artículos relacionados