Why typescript enum is seen as possibly undefined in strict mode? How to fix?

Viewed 21

I'm getting an error from Typescript (4.8.2) STRICT:

Argument of type 'State | undefined' is not assignable to parameter of type 'State'.
  Type 'undefined' is not assignable to type 'State'. ts(2345)

using this code:

enum State {
  Completed = "COMPLETED",
  Discontinued = "DISCONTINUED",
}

type Player = {
  description: Scalars["String"];
  state: State;
  team?: Maybe<Team>;
};

let player: Partial<Player>;

const isOK = [State.Completed, State.Discontinued].includes(player.state);

How can I fix?

It's because of Partial<Player>?

1 Answers

Yes, a Partial<Player> might not have a defined state, and TypeScript's typings for the includes() method of arrays requires that the searched item be assignable to the array element types. (See Why does the argument for Array.prototype.includes(searchElement) need the same type as array elements?)

The easiest way to deal with this is to eliminate the possibility of undefined by checking for it explicitly before you use includes():

const isOK = (player.state !== undefined) &&
    [State.Completed, State.Discontinued].includes(player.state);

Playground link to code

Related