Home > Blockchain >  Typescript make type from values of class parameters
Typescript make type from values of class parameters

Time:09-30

I have a class with two properties

class X {
  S1: string = "Hello"
  S2: string = "World"
}

I would like to create a type that resolves to the union of the strings values: "Hello" | "World"

I was thinking of using something like the keyof operator, the only problem with that is that it yields string instead of the actual value.

type V = X[keyof X]

CodePudding user response:

The most ergonomic way of doing it would be to remove the explicit type annotation from the field and use an as const assertion on the value to preserve the literal type:

class X {
  S1 = "Hello" as const
  S2 = "World" as const
}
type V = X[keyof X]

enter image description here

  • Related