Home > Software design >  Typescript: Get value type of Enum
Typescript: Get value type of Enum

Time:01-07

enum Test {A,B};
const x = { name:"Test", value:Test.B };
const y = typeof x.Value;

The value of y is "Number", May I know it is possible to get Test of type?

CodePudding user response:

typeof in a value position is a javascript operator, not a typescript one. It always returns the same union of string literals at the type level.

const test = typeof false
// "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"

See playground

But at runtime, a.value is just a number.

enum Test {A,B};
const a = { name: "Test", value: Test.B }
console.log(a.value) // 1

So typeof a.value is 'number' because typeof 1 is 'number'.

Which means that at runtime, you cannot get a reference to an an enum which you only have a member of that enum. The member does not encode any information about where it came from.


But that's what your types are for.

You can use typeof in a type declaration to get the Typescript type of a any value. This a totally different operator.

enum Test {A,B};
const a = { name: "Test", value: Test.B }
type B = typeof a['value'] // Test

See playground


Without more details about your goal, I can't rally give any more specific advice.

CodePudding user response:

typeof Test

{
  "0": "A",
  "1": "B",
  "A": 0,
  "B": 1
} 

Here, Test is a numeric enum.

Overall, An enum is a real object at runtime. means it is object defined as const.

  • Related