string[] 和非定长字符串元组有什么区别?

时间:2021-08-01 13:14:07

标签: typescript

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

StringTuplestring[] 有什么区别? 两者都是不定长的字符串数组,但不相等。

更新:

感谢@Kelvin Schoofs。我明白了:

移除起始 string 后,StringTuple do 等于 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!

1 个答案:

答案 0 :(得分:0)

您的 StringTuple 被定义为string 开头。你不能例如将一个空数组(甚至 string[]!)分配给 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)