我需要一种方法来输入一个对象,其中键是特定类型的“事件”字段的值,值是一个回调函数的数组,该函数接受相同类型的数据子类型的对象。
我已经尝试使用映射类型,但由于我是TypeScript的初学者,因此对此感到非常困惑。
// 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 => {}],
};
如果这有帮助的话,我很高兴重构上面任何内容。