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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With