首页 > 解决方案 > TypeScript:在复杂类型中组合枚举

问题描述

我在 TypeScript 3.7.5 中有两个enums 和 a const,我想用enums 来写一个相当复杂type的常量

enum Action {
  Jump,
  Run,
  Shoot,
}

enum Character {
  Foo,
  Bar,
}

type IDontKnow = ...;

const actions: IDontKnow = {
  [Character.Foo]: {
    [Action.Jump]: false,
    [Action.Run]: true,
    [Action.Shoot]: false,
  },
  [Character.Bar]: {
    [Action.Jump]: false,
    [Action.Run]: true,
    [Action.Shoot]: true,
  },
};

enum问题是我通常在使用s 或不知道对象将有多少键时使用方括号来表示类型,但我认为我不能同时使用这两个键:

const usingEnums: { [Character]: string; } = {
  [Character.Foo]: 'John'
};

const usingArray: { [name: string]: Action[] } = {
  'John': [Action.Run, Action.Shoot],
  'Jane': [Action.Jump, Action.Run, Action.Shoot]
};

有什么想法吗?

标签: typescripttypesenums

解决方案


您可以创建一个映射类型,其中键为Character枚举,内部对象使用Action枚举作为键:

type IDontKnow = {
    [key in Character]: {
        [key in Action]: boolean
    }
};

操场


推荐阅读