1

I'm trying to use typescript with graphql, and their enum systems are causing some headaches for me. I'm using number indexed enums, without specifying the value on the ts enum like:

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

Are there any workarounds for this?

1 Answer 1

1

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
}

enter image description here

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.

Personaly, I think you should avoid numeric enums, and use enum Foo {A='A'}

Sign up to request clarification or add additional context in comments.

2 Comments

I don't like them either, but mongoose doesn't support custom sorting functions. So fields like status, where the values are ranked, I had to encode them to numbers. However, your answer still doesn't make this "aah makes sense" to me. If the enum wouldn't be numbered, but A = 'A', and instead of A[0] I get A['A'], it's still a string.
You can also use immutable objects. Like: const obj={A:0} as const

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.