gpt4 book ai didi

javascript - TypeScript - 从对象创建联合

转载 作者:搜寻专家 更新时间:2023-10-30 20:57:09 25 4
gpt4 key购买 nike

我正在用 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 } | {
类型:'onNumberReceived',有效载荷:{ 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

关于javascript - TypeScript - 从对象创建联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50672765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com