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

若如初见. 提交于 2020-07-18 11:00:28

问题


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?


回答1:


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



回答2:


As Foo is the enum so you can use the . as well to accesss the value of enum like below

var foo : Foo = Foo.A;



回答3:


As described into the typescript enum documentation

you can use it in different ways :

Enum.A // Good way

Enum["A"] // Bad way

Enum[variable] // Good way

In your case

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

// Bad way
const example1 : Foo = Foo["A"];

// Good way
const example2 : Foo = Foo.A;

// Good way
const example3 : Foo = Foo[variable];

You should AVOID the use of example1 and focus on example2 and example3. In any case, there is no point to write "A".

Always prefer Enum.A and if you want to cast a variable as an enum use Enum[variable].




回答4:


While not a direct answer to the question per se (as it doesn't assign to enum but a derivative type), I discovered this which does solve my problem of allowing me to assign a string and guarantees that it's a part of the enum, and even allows me to avoid the redundant A = "A" when all that really matters is A.

You can use keyof [1] to enumerate the properties on the typeof the enum (Foo)

enum Foo {
    A,
    B
}

var foo : keyof typeof Foo = "A"; // OK
var foo : keyof typeof Foo = "C"; // ERROR

Or on objects:

interface Bar {
    type: keyof typeof Foo
}

let obj: Bar = {
    type: "A" // OK
}

[*] I'll mark one of the other answers as accepted and keep this here for reference



来源:https://stackoverflow.com/questions/50464141/cannot-assign-a-string-value-to-typescript-enum-initializer-type-string-not-ass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!