如何将联合类型指定为对象键Typescript

时间:2019-09-04 08:38:24

标签: typescript typescript-generics generic-type-argument union-types

我需要一种键入对象的方法,其中键是特定类型的'event'字段的值,而值是采用相同类型的数据子类型。

我曾尝试使用映射类型,但我是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 => {}],
};

如果有帮助,我很高兴对以上任何内容进行重组。

1 个答案:

答案 0 :(得分:3)

我们本质上需要的是一种通过提供事件名称来查找整个事件类型的方法。这可以使用conditional helper type

来完成
type EventByName<E extends WSEvent['event'], T = WSEvent> = T extends {event: E} ? T : never;

第一个通用参数E必须是事件名称之一。第二个是我们要缩小范围的联合类型。它默认为WSEvent,因此无需指定它。然后,条件表达式仅以并集类型返回扩展{event: E}(其中E是事件名称)的那些事件。

一旦有了助手类型,就可以很容易地为回调调整现有的映射类型:

type Callbacks = {
  [E in WSEvent['event']]: ((data: EventByName<E>['data']) => void)[];
};

Playground


关于callbacks名称的注释。建议对类型使用PascalCase。这样可以更轻松地与变量区分开。在示例中,我将其更改为Callbacks