[英]TypeScript - Create Union From Object
I'm creating an EventEmitter in typescript, and I can't figure out a way to do the following: 我正在使用typescript创建一个EventEmitter,我无法找到一种方法来执行以下操作:
Say I have an interface like this: 说我有这样的界面:
interface EventEmitterSubscription { dispose(): void }
// here it is
interface EventEmitter<T extends { [key: string]: any }> {
onAnyEvent(callback: (event: { type: ???, payload: ??? }) => void): EventEmitterSubscription
// ...
}
I can't find a way to type the onAnyEvent
callback such that, for example, for an eventEmitter like this: 我找不到一种方法来输入
onAnyEvent
回调,例如,对于像这样的eventEmitter:
EventEmitter<{ onNumberReceived: number, onCatReceived: { cat: ICat }, onPersonNameReceived: string }>
The onAnyEvent
field would have the type onAnyEvent
字段将具有该类型
onAnyEvent(callback: (event: { type: 'onNumberReceived', payload: number } | { type: 'onCatReceived', payload: { cat: ICat } } | { type: 'onPersonNameReceived', payload: string }) => void): EventEmitterSubscription
Currently my implementation has the interface look like: 目前我的实现界面如下:
onAnyEvent(callback: (event: { type: keyof T, payload: T[keyof T] }) => void): EventEmitterSubscription
except that currently doesn't work, as for example that would produce the types onAnyEvent(callback: (event: { type: 'onNumberReceived', payload: number } | { type: 'onNumberReceived', payload: { cat: ICat } } | /* ... */) => void): EventEmitterSubscription
除了当前不起作用,例如会产生类型
onAnyEvent(callback: (event: { type: 'onNumberReceived', payload: number } | { type: 'onNumberReceived', payload: { cat: ICat } } | /* ... */) => void): EventEmitterSubscription
So how can I type the onAnyEvent
field? 那么如何键入
onAnyEvent
字段?
One possible way to create a union is to have a mapped type with each property having the type of one element of desired union, like this: 创建联合的一种可能方法是使用映射类型,每个属性具有所需联合的一个元素的类型,如下所示:
type EventTypeMap<T extends { [key: string]: {} }> =
{ [K in keyof T]: { type: K; payload: T[K] } };
Then you can define generic union type 然后,您可以定义通用联合类型
type CallbackEventTypes<T extends { [key: string]: {} }> =
EventTypeMap<T>[keyof EventTypeMap<T>]
and use it 并使用它
interface EventEmitterSubscription { dispose(): void }
interface EventEmitter<T extends { [key: string]: {} }> {
onAnyEvent(callback: (event: CallbackEventTypes<T>) => void): EventEmitterSubscription
// ...
}
interface ICat { meow() }
type Emitter = EventEmitter<{ onNumberReceived: number, onCatReceived: { cat: ICat }, onPersonNameReceived: string }>
type HandlerType = Emitter['onAnyEvent'];
// inferred as
//type HandlerType =
// (callback: (event: { type: "onNumberReceived"; payload: number; }
// | { type: "onCatReceived"; payload: { cat: ICat; }; }
// | { type: "onPersonNameReceived"; payload: string; }
// ) => void) => EventEmitterSubscription
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.