Alain D'Ettorre
Alain D'Ettorre

Reputation: 144

TypeScript: combine enums in a complex type

I have two enums and a const in TypeScript 3.7.5 and I'd like to use enums to write a quite complex type for a constant

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,
  },
};

The problem is I normally use square brackets for types either when using enums or when not knowing how many keys an object will have, but I can't use both I think ex.:

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

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

Any thoughts?

Upvotes: 1

Views: 550

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37958

You can create a mapped type with the keys as Character enum and inner object using Action enum as a keys:

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

Playground

Upvotes: 2

Related Questions