简体   繁体   English

TypeScript 枚举键 - 字符串不可分配给类型 Enum

[英]TypeScript enum key - string is not assignable to type Enum

I'm trying to use typescript with graphql, and their enum systems are causing some headaches for me.我正在尝试将 typescript 与 graphql 一起使用,它们的枚举系统让我有些头疼。 I'm using number indexed enums, without specifying the value on the ts enum like:我正在使用数字索引枚举,而没有指定 ts 枚举上的值,例如:

enum Enum { A }

Because graphql enums can't have numbers, I'm having a custom resolver to convert the string value to the corresponding index.因为 graphql 枚举不能有数字,所以我有一个自定义解析器来将字符串值转换为相应的索引。 For test what I'm trying to do is:为了测试我想要做的是:

const a: Enum = Enum[Enum.A]

However, I'm getting an error of:但是,我收到以下错误:

Type 'string' is not assignable to type 'Enum'.(2322)

I'm sort of getting the logic behind, because in [] I could put key that doesn't exist on the enum, but the key itself is the enum itself, so it should be enough confidence for it to return the enum, not just string.我有点理解背后的逻辑,因为在[]我可以放置枚举中不存在的键,但键本身就是枚举本身,所以它应该有足够的信心返回枚举,而不是只是字符串。 And because Object.values(Enum) is returning both the keys, and values, getting the key should still be enum.并且因为Object.values(Enum)返回键和值,所以获取键仍然应该是枚举。

Are there any workarounds for this?是否有任何解决方法?

This code:这段代码:

enum Enum { A }

Compiles to:编译为:

var Enum;
(function (Enum) {
    Enum[Enum["A"] = 0] = "A";
})(Enum || (Enum = {}));

Which in turn, compiles to反过来,编译为

{
  0:'A'
 'A':0
}

在此处输入图片说明

Hence, this code:因此,这段代码:

const a: Enum = Enum[Enum.A]

Means literaly this:字面意思是:

const a: Enum = Enum[0]

Accordingly, above code compiles to:因此,上面的代码编译为:

const a: Enum = 'A'

String A is not assignable to enum, since your enum is numeric.字符串A不可分配给枚举,因为您的enum是数字。

Personaly, I think you should avoid numeric enums, and use enum Foo {A='A'}就个人而言,我认为您应该避免使用数字枚举,并使用enum Foo {A='A'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM