首页 > 解决方案 > 打字稿中字符串键索引器的更好类型安全性

问题描述

我创建了这个游乐场,代码如下:

export enum KeyCode {
  Alt = 'meta',
  Command = 'command',
  // etc.
}

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 buildShortcuts = (map: Shortcut) => {
  return []
}

function getShortcuts(shortcutMap: ShortcutMap, mapKey?: keyof typeof shortcutMap){
  const map = mapKey ? shortcutMap[mapKey] : shortcutMap;
  return buildShortcuts(map);
}

export const shortcutMapWithoutKey: ShortcutMap = {
  MOVE_LEFT: [KeyCode.Alt, 'a'],
  MOVE_RIGHT: [KeyCode.Command, 'd'],
};

export const shortcutMapWithKey: ShortcutMap = {
  one: {
    MOVE_UP: [KeyCode.Alt, 'b'],
    MOVE_DOWN: [KeyCode.Command, 'e'],
  },
  two: {
    MOVE_HERE: [KeyCode.Alt, 'c'],
    MOVE_THERE: [KeyCode.Command, 'f'],
  }
};

const a = getShortcuts(shortcutMapWithoutKey);
const b = getShortcuts(shortcutMapWithKey, "one");

ShortcutMap 类型无法充分缩小联合类型。

是否可以通过某种方式缩小联合来获得更好的类型安全性。

我在这一行得到一个错误:

  return buildShortcuts(map);

'string | 类型的参数 组合 | 字符串[] | 序列 | 快捷方式 | { [键:字符串]:快捷方式;}' 不可分配给“快捷方式”类型的参数。类型“字符串”不可分配给类型“快捷方式”。

标签: typescript

解决方案


I think part of your type confusion comes from the fact that you define your ShortcutMap as

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

I would expect here, that a map is just

  {
      [key: string]: Shortcut;
  }

One solution for you would be to make your types more explicit/narrow by avoiding the union type.

Have a look at this TypeScript playground.

Hope, that helps.


推荐阅读