redsun
redsun

Reputation: 13

Typescript make type from values of class parameters

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]

Upvotes: 0

Views: 33

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

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]

Playground Link

Upvotes: 1

Robert Rendell
Robert Rendell

Reputation: 2289

Maybe not ideal, but an option is to use literal types:

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

type V = X[keyof X]

enter image description here

Upvotes: 0

Related Questions