Typescript enums typing error (argument of type 'string' is not assignable to parameter of type)

Viewed 9447

I have an enum define as follows:

export enum taskTypes {
  WORK = 'work',
  SLEEP = 'sleep',
  EXERCISE = 'exercise',
  EAT = 'eat'
}

On the top of my class I define the currentTask as follows:

private currentTask: string;

However, when I use the enums in [WORK, SLEEP].includes(currentTask) I get the following error.

Argument of type 'string' is not assignable to parameter of type 'currentTask'

The weird thing is when I simply just change it to use the actual string it doesn't complain.

['work', 'sleep'].includes(currentTask) ===> this works.

So what am I missing here?

1 Answers

currentTask is of type string, but WORK and SLEEP is enum members of type taskTypes

So [WORK, SLEEP] is an array of taskTypes enums. Such an array can never contain a string.

['work', 'sleep'] is an array of strings, which can contain a string.

If you type the private memeber to be of type taskTypes it will also work

private currentTask: taskTypes
Related