zok
zok

Reputation: 7882

construct string union type from keys of custom type in TypeScript

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>

Upvotes: 0

Views: 52

Answers (1)

hendra
hendra

Reputation: 2651

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

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

type MyfieldsKeys = keyof MyFields;

Upvotes: 1

Related Questions