gpt4 book ai didi

arrays - 固定长度的元组

转载 作者:搜寻专家 更新时间:2023-10-30 20:37:35 24 4
gpt4 key购买 nike

元组中的 Typescript 允许添加以前使用过的任何类型的额外元素,但我想限制长度。我试过 & { length: 2 } , but it didn't helped :

declare var a: [string, number] & { length: 2 };

a[0] = "1"
a[1] = 2;
a[2] = "3";
a[3] = 4;

[2][3] 的赋值不会产生错误。如何指定对应的类型?

最佳答案

使用类型 never for array tail :

declare var a: [string, number, ...never[]];

你会得到

Type '"3"' is not assignable to type 'never'.

Type '4' is not assignable to type 'never'.

关于arrays - 固定长度的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52485154/

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