声明至少含2个元素的数组类型时为何出现报错?
为何声明至少包含2个元素的数组类型时会报错?
原始代码
type StringArray = readonly string[]; type stringArrayWith2Elements = [string, string]; type stringArrayWith2PlusElements = StringArray & { 1: string; } const myArr: stringArrayWith2PlusElements = ['a', 'b'];
报错信息
Type 'string[]' is not assignable to type 'stringArrayWith2PlusElements'.
Property '1' is missing in type 'string[]' but required in type '{ 1: string; }'.
原因分析
TypeScript 中,readonly string[](数组类型)的索引签名是[index: number]: string,但它不会强制要求具体的数字索引(如1)必须存在——因为数组可以是长度为0或1的,TypeScript不会默认给数组类型预设索引1及以上的必选属性。
当你用交叉类型StringArray & {1: string}时,要求该类型必须同时满足数组的特性,且必须拥有索引1的属性。但['a','b']会被TypeScript推断为string[],而string[]并不被认定为一定包含索引1的属性,因此会触发类型不兼容的错误。
而当你同时指定索引0和1为必选属性时,TypeScript会识别出这个类型代表至少包含2个元素的数组:数组天然支持索引0,加上索引1的必选要求,['a','b']这样的数组实例确实同时拥有这两个索引的元素,因此类型检查通过。
修改后的可行代码
type StringArray = readonly string[]; type stringArrayWith2Elements = [string, string]; type stringArrayWith2PlusElements = StringArray & { 0: string; 1: string; } const myArr: stringArrayWith2PlusElements = ['a', 'b'];
内容的提问来源于stack exchange,提问作者KingMario
相关产品推荐
相关产品推荐

