0

How can I construct a string union type in TypeScript that is based on the keys of a custom type? Of course it would only work if they're all strings.

Let's say I have this:

type MyFields {
  name: string
  email: string
  password: string
}

How could I generate something like that:

type MyFieldsKeys = 'name' | 'email' | 'password'

Does such a feature exist?

It'a kind of the opposite of what Record does - I could for instance generate MyFields from MyfieldsKeys with Record by doing MyFields = Record<MyFieldsKeys, string>

1 Answer 1

1

Use keyof to produce a string or numeric literal union of keys.

type MyFields = {
  name: string
  email: string
  password: string
}

type MyfieldsKeys = keyof MyFields;
Sign up to request clarification or add additional context in comments.

Comments

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.