typescript可选的返回相同类型的索引器类型

时间:2019-03-24 16:41:53

标签: typescript

我有以下几种类型:

export enum KeyCode {
  Alt = 'meta',
  Command = 'command',
  Ctrl = 'ctrl',
  DownArrow = 'down',
  Enter = 'enter',
  Escape = 'esc',
  LeftArrow = 'left',
  Mod = 'mod',
  RightArrow = 'right',
  UpArrow = 'up'
}


export interface ShortcutAction {
  keys: string | string[];
  action: string;
}

export type ShortcutHandler = (action: string, event: KeyboardEvent) => void;

export type KeyStroke = KeyCode | string;

export interface Combination {
  combination: KeyStroke[];
}

export interface Sequence {
  sequence: KeyStroke[];
}

export type ShortcutItem = KeyStroke | KeyStroke[] | Combination | Sequence;

export interface Shortcut {
  [key: string]: ShortcutItem;
}

export type ShortcutMap =
  | {
      [key: string]: Shortcut;
    }
  | Shortcut;

export const buildFromMap = (shortcutMap: ShortcutMap, key?: string ) => {
  const map = key ? shortcutMap[key] : shortcutMap;

  return buildShortcuts(map);
}

export const buildShortcuts = (map: Shortcut): ShortcutAction[] => {
  return [];
}

const singleShortcutMap: ShortcutMap = {
  MOVE_LEFT: [KeyCode.LeftArrow, 'a'],
  MOVE_RIGHT: [KeyCode.RightArrow, 'd']
};

const multipleShortcutMap: ShortcutMap = {
  key1: {
    MOVE_UP: 'a'
  },
  key2: {
    MOVE_UP: 'a'
  }
};

buildFromMap(singleShortcutMap);
buildFromMap(multipleShortcutMap, "key1");

我希望ShortcutMap类型能够定义以下两个示例:

const singleShortcutMap: ShortcutMap = {
  MOVE_LEFT: [KeyCode.LeftArrow, 'a'],
  MOVE_RIGHT: [KeyCode.RightArrow, 'd']
};

const multipleShortcutMap: ShortcutMap = {
  key1: {
    MOVE_UP: 'a'
  },
  key2: {
    MOVE_UP: 'a'
  }
};

因此,它可以可选地具有返回Shortcut类型的键,或者它是Shortcut类型的键。

我已经尝试过了:

export type ShortcutMap =
  | {
      [key: string]: Shortcut;
    }
  | Shortcut;

但是它显示为:

string | {
    [key: string]: Shortcut;
} | Shortcut | string[] | Combination | Sequence

所以我认为我没有适当地缩小类型,但是我不确定在这种情况下该怎么做。

我创建了一个playground to illustrate this

0 个答案:

没有答案