简体   繁体   English

打字稿中的字符串键索引器具有更好的类型安全性

[英]better type safety for string key indexer in typescript

I've created this playground and here is the code: 我已经创建了这个游乐场 ,这里是代码:

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");

The ShortcutMap type is not able to narrow the union type sufficiently. ShortcutMap类型不能充分缩小联合类型。

Is it possible to get better type safety by somehow narrowing the union. 是否可以通过某种方式缩小联合来获得更好的类型安全性。

I get an error on this line: 我在这条线上出现错误:

  return buildShortcuts(map);

Argument of type 'string | 类型'string |的参数 Combination | 组合| string[] | 字符串[] | Sequence | 顺序| Shortcut | 快捷方式 { [key: string]: Shortcut; {[key:string]:快捷方式; }' is not assignable to parameter of type 'Shortcut'. }”不能分配给“快捷方式”类型的参数。 Type 'string' is not assignable to type 'Shortcut'. “字符串”类型不能分配给“快捷方式”类型。

I think part of your type confusion comes from the fact that you define your ShortcutMap as 我认为您造成类型混淆的部分原因是您将ShortcutMap定义为

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 . 看看这个TypeScript游乐场

Hope, that helps. 希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM