Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign a string value to typescript enum (Initializer type string not assignable to variable type)

It seems that from TypeScript 2.4 onwards String Enums are a feature.

However the following does not work:

enum Foo {
    A = "A",
    B = "B"
}

var foo : Foo = "A";

Initializer type string not assignable to variable type Foo

String literals work:

type Foo = "A" | "B";

But what if I want to use an enum? Is there a way around this?

like image 826
ᴘᴀɴᴀʏɪᴏᴛɪs Avatar asked May 22 '18 09:05

ᴘᴀɴᴀʏɪᴏᴛɪs


People also ask

How do I fix undefined string is not assignable to type string?

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 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.

How do I convert a string to enum in TypeScript?

To convert a string to an enum: Use keyof typeof to cast the string to the type of the enum. Use bracket notation to access the corresponding value of the string in the enum.

Can I use enum as a type in TypeScript?

Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.


1 Answers

You can use an index expression to get the value of the enum:

enum Foo {
    A = "A",
    B = "BB"
}

var foo : Foo = Foo["A"];
var fooB : Foo = Foo["B"];

Note that the key will be the name of the member not the value.

You could also use a type assertion, but you will not get errors if you assign a wrong value:

var foo : Foo = "A"  as Foo;
var foo : Foo = "D"  as Foo; // No error
like image 186
Titian Cernicova-Dragomir Avatar answered Nov 02 '22 15:11

Titian Cernicova-Dragomir