阅读有关rest elements in tuple types并试图弄清楚如何提取类型的通用部分:
type Attribute<Type> = { id: string, type?: Type };
type Position = { x: number, y: number };
let Position: Attribute<Position> = { id: "position" };
type Status = "active" | "inactive";
let Status: Attribute<Status> = { id: "status" };
我确定有一种写条件类型的方法,该条件类型会将各种Attribute<T>
的元组映射到各种T
的元组。
type AttributeTypes<Attributes extends Attribute<any>[]> =
Attributes extends Attribute<infer T> ? T[] : never;
type Result = AttributeTypes<[typeof Position, typeof Status]> // should be `[Position, Status]`
但是我对推理步骤的理解不够充分,它总是以never
分支结束。
条件类型没有理由在元组上工作,您的条件类型基本上解决了问题[typeof Position, typeof Status] extends Attribute<infer T>
,但它显然没有,因此您永远都无法使用。