我正在用 typescript 创建一个EventEmitter,但我想不出一种方法来执行以下操作:

说我有一个这样的界面:

interface EventEmitterSubscription { dispose(): void }

// here it is
interface EventEmitter<T extends { [key: string]: any }> {
  onAnyEvent(callback: (event: { type: ???, payload: ??? }) => void): EventEmitterSubscription
  // ...
}

我找不到一种方法来键入onAnyEvent回调,例如,对于这样的eventEmitter:
EventEmitter<{ onNumberReceived: number, onCatReceived: { cat: ICat }, onPersonNameReceived: string }>
onAnyEvent字段的类型为
onAnyEvent(callback: (event: { type: 'onNumberReceived', payload: number } | { type: 'onCatReceived', payload: { cat: ICat } } | { type: 'onPersonNameReceived', payload: string }) => void): EventEmitterSubscription

目前,我的实现具有如下界面:
onAnyEvent(callback: (event: { type: keyof T, payload: T[keyof T] }) => void): EventEmitterSubscription

除非当前不起作用,例如会产生onAnyEvent(callback: (event: { type: 'onNumberReceived', payload: number } | {type: 'onNumberReceived', payload: { cat: ICat } } | /* ... */) => void): EventEmitterSubscription类型

那么如何键入onAnyEvent字段?

最佳答案

创建联合的一种可能方法是具有一个映射类型,每个属性都具有所需联合的一个元素的类型,如下所示:

type EventTypeMap<T extends { [key: string]: {} }> =
    { [K in keyof T]: { type: K; payload: T[K] } };

然后您可以定义通用联合类型
type CallbackEventTypes<T extends { [key: string]: {} }> =
     EventTypeMap<T>[keyof EventTypeMap<T>]

并使用它
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

09-06 05:21