0

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]
2
  • 1
    I think it's impossible, because the value "Hello" and "World" only be create/assign at runtime, so we can't define a "type that resolves to the union of the strings" when it's not even be created. Commented Sep 29, 2022 at 10:39
  • @Fresher Well you can with static parameters, so I don't see why there isn't a way to do it with non-static parameters. Commented Sep 29, 2022 at 10:42

2 Answers 2

1

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

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

Comments

0

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

1 Comment

Yea I know, but this isn't really what I'm trying to do.

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.