例如,假设有下面的代码。
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); // i want this type "MyType[]" !!!
};
func(a);
我希望“myTypeArr”变量被推断为MyType[]。
然而,实际上被推断为 (number | MyType)[]。
我进行了搜索来实现它,但我做不到。
可以使用解构来实现这一点:
type MyType = 'a' | 'b' | 'c';
const a = [3, 5, 'a', 'b'] as const;
const func = (arg: readonly [number, number, ...MyType[]]) => {
const [ , , ...myTypeArr] = arg;
};
func(a);