如何让元组slice出的数组自动推断为指定MyType[]类型?
解决TypeScript中slice返回类型推断错误的问题
问题分析
TypeScript的slice方法对元组的类型推断存在局限——哪怕函数参数明确是readonly [number, number, ...MyType[]],调用slice(2)时,TS无法识别从索引2开始的元素均为MyType类型,因此会返回(number | MyType)[]这种联合类型数组。
可行解决方案
方案1:直接类型断言
最简单的方式是显式给slice的返回值做类型断言,强制指定为MyType[]:
type MyType = 'a' | 'b' | 'c'; const a = [3, 5, 'a', 'b'] as const; const func = (arg: readonly [number, number, ...MyType[]]) => { const myTypeArr = arg.slice(2) as MyType[]; }; func(a);
方案2:利用数组解构
如果元组的前缀长度固定(这里是前两个number类型元素),可以通过解构直接提取后续元素,TS会自动正确推断类型:
type MyType = 'a' | 'b' | 'c'; const a = [3, 5, 'a', 'b'] as const; const func = (arg: readonly [number, number, ...MyType[]]) => { const [, , ...myTypeArr] = arg; // myTypeArr自动推断为MyType[] }; func(a);
方案3:封装类型安全的工具函数
如果需要在多个地方复用这个逻辑,可以封装一个专属工具函数,内部处理断言,对外暴露正确类型:
type MyType = 'a' | 'b' | 'c'; type TargetTuple = readonly [number, number, ...MyType[]]; function getMyTypePart(tuple: TargetTuple): MyType[] { return tuple.slice(2) as MyType[]; } const a = [3, 5, 'a', 'b'] as const; const func = (arg: TargetTuple) => { const myTypeArr = getMyTypePart(arg); // 自动推断为MyType[] }; func(a);
内容的提问来源于stack exchange,提问作者dom wis
相关产品推荐
相关产品推荐

