JFo*_*ter 4 generic-type-argument typescript typescript-generics union-types
我需要一种输入对象的方法,其中键是特定类型的“事件”字段的值,值是回调数组,该数组采用相同类型数据子类型的对象。
我曾尝试使用映射类型,但我是打字稿的初学者并且真的很挣扎。
// I have this type structure, where the event is always a string, but the data can be anything (but is constrained by the event)
interface EventTemplate {
event: string;
data: any;
}
export interface CreateEvent extends EventTemplate {
event: 'create_game';
data: {
websocketID: 'string';
};
}
export interface JoinEvent extends EventTemplate {
event: 'join_game';
data: {
gameID: 'string';
};
}
export interface MessageEvent extends EventTemplate {
event: 'message';
data: string;
}
export type WSEvent = CreateEvent | JoinEvent | MessageEvent;
// I want an object like this
type callbacks = {
[key in WSEvent['event']]: ((data: WSEvent['data']) => void)[];
};
// Except that it forces the data structure to match with the key used. IE using a specific WSEvent rather than a generic one
// Something along the lines of:
type callbacks = {
[key in (T extends WSEvent)['event']]: ((data: T['data']) => void)[];
};
// ...only valid..
const callbacks: callbacks = {
// So this should be valid:
message: [(data: MessageEvent['data']): void => {}, (data: MessageEvent['data']): void => {}],
// But this should not be valid, as CreateEvent doesn't have the event 'join_game'
join_game: [(data: CreateEvent['data']): void => {}],
};
Run Code Online (Sandbox Code Playgroud)
如果有帮助,我很乐意重组上述任何内容。
我们本质上需要的是一种通过提供事件名称来查找整个事件类型的方法。这可以使用条件助手类型来完成
type EventByName<E extends WSEvent['event'], T = WSEvent> = T extends {event: E} ? T : never;
Run Code Online (Sandbox Code Playgroud)
第一个通用参数E必须是事件名称之一。第二个是我们试图缩小范围的联合类型。它默认为WSEvent因此无需指定它。然后条件表达式只返回那些在联合类型中扩展的事件{event: E}(其中E是事件名称)。
一旦我们有了辅助类型,就很容易相应地调整现有的回调映射类型:
type Callbacks = {
[E in WSEvent['event']]: ((data: EventByName<E>['data']) => void)[];
};
Run Code Online (Sandbox Code Playgroud)
关于名称的旁注callbacks。对于类型,建议使用 PascalCase。它可以更容易地与变量区分开来。我在示例中将其更改为Callbacks.
| 归档时间: |
|
| 查看次数: |
6154 次 |
| 最近记录: |