Typescript: How to use key type as enum in an object keeping all enum values as optional?

Viewed 200

I am using a enum type as key for an object:

enum Level {
  Novice, Intermediate, Pro
}

type Players = { [key in Level] : string[]}

Upon trying to create an object of type players with just Novice and Pro, I get the error saying Intermediate is not present:

const mapping: Players = {
  [Level.Novice]: ["Neo"],
  [Level.Pro]: ["John Wick"]
}

How do I make it work?

1 Answers

I found out that this can be done by marking the key as optional in the type

type Players = { [key in Level]? : string[]}

Please notice the '?' which lies outside the []

I thought it was a good learning so I shared by answering my own question.

Related