Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 538
lion_bash Avatar asked Oct 21 '19 22:10

lion_bash


People also ask

Is not assignable to type enum TypeScript?

The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion. Here is the first example of how the error occurs.

Is not assignable to parameter of type TypeScript?

The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.

Is not assignable to type string undefined?

The "Type 'string | undefined' is not assignable to type string" error occurs when a possibly undefined value is assigned to something that expects a string . To solve the error, use the non-null assertion operator or a type guard to verify the value is a string before the assignment.

Is not assignable to parameter of type object?

The error "Argument of type is not assignable to parameter of type 'never'" occurs when we declare an empty array without explicitly typing it and attempt to add elements to it. To solve the error, explicitly type the empty array, e.g. const arr: string[] = []; . Here are 2 examples of how the error occurs.


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
like image 194
Klas Mellbourn Avatar answered Sep 29 '22 12:09

Klas Mellbourn