3

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 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.