【发布时间】:2023-03-28 22:14:01
【问题描述】:
我想使用条件类型作为休息参数,但当我第一次进行测试时我很惊讶
这是playground,这是代码:
type ExtractParts<P extends any[]> =
P extends [infer H, ...infer U]
? ['yes way']
: ['no way']
interface A {
description: string;
action: () => {
say: string;
it: string;
};
}
type Q = ExtractParts<[1,2,3]> // ['yes]
type P = ExtractParts<A[]>; // ['no way']
type R = ExtractParts<[{ // ['yes way']
description: string;
action: () => {
say: string;
it: string;
};
}]>;
我对这种行为感到惊讶
type P = ExtractParts<A[]>; // ['no way']
但这正如我所想,因为它是一个严格的元组
type R = ExtractParts<[{ // ['yes way']
description: string;
action: () => {
say: string;
it: string;
};
}]>;
我想将此技术与休息参数一起使用
type ExtractParts<P extends any[]> =
P extends [infer H, ...infer U]
? ['yes way']
: ['no way']
function parts<P extends any[]>(...parts: ExtractParts<P>){}
const b = parts(1,2,3);
但是P extends [infer H, ...infer U] 返回 false
我可以使用这样的条件类型来推断休息参数的头部和尾部吗?
【问题讨论】:
标签: typescript