gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:47:05 26 4
gpt4 key购买 nike

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 等于 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!

最佳答案

您的StringTuple 定义为字符串 开头。你不能,例如将一个空数组(甚至 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)

关于typescript - string[] 和非定长字符串元组有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68610761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com