【发布时间】:2019-11-07 02:01:29
【问题描述】:
如何键入我的create 函数,以便它可以安全地推断它收到的每一对的单独类型?
type Component<T=any> = { id: string, _type?: T };
type Pair<T=any> = [Component<T>, T];
function create<T extends Pair[]>(...pairs: T) {
// ...
}
type Vector = [number, number];
type Status = "active" | "idle";
let Position: Component<Vector> = { id: "position" };
let Status: Component<Status> = { id: "status" };
let entity = create(
[Position, [0, 0]],
[Status, false], // should fail as it expects `Status` and got `boolean`
);
我可以通过显式传递类型参数来实现所需的行为。
let entity = create<[
Pair<Vector>,
Pair<Status>,
]>(
[Position, [0, 0]],
[Status, false], // should fail as it expects `Status` and got `boolean`
);
我的预感是,一旦编译器已经将 pairs 参数推断为 Pair[] 类型,编译器就不会尝试从它们的元素推断嵌套的 Pair 类型。
【问题讨论】:
-
你刚刚用 Pait
定义了 Pair,所以 Pair 的类型是 [Component , any]... -
我知道。这就是为什么我试图弄清楚如何推断该类型。
标签: typescript