type EventConfig<Events extends { kind: string }> = {
[E in Events as E["kind"]]: (event: E) => void;
}
type SquareEvent = { kind: "square", x: number, y: number };
type CircleEvent = { kind: "circle", radius: number };
type Config = EventConfig<SquareEvent | CircleEvent>
//type Config = {
square: (event: SquareEvent) => void;
circle: (event: CircleEvent) => void;
}
[E in Events as E["kind"]]
这段代码不太理解,如果写成 E in keyof Events
能理解成E
是Events对象的每一个key,但是直接E in Events
那这个E
代表什么呢?
in
可以遍历联合类型中的每一个类型K
依次为TypeA
,TypeB
和TypeC