Peeyush Kushwaha
Peeyush Kushwaha

Reputation: 3623

Declaring keys ("key1" | "key2") first and then enforcing that another object type must have those keys

Usually in typescript you'd use the pattern that you declare a type:

type O = {"key1": string, "key2": int}

and then you can declare

type keyNames = keyof O

But is it possible to do the opposite? i.e. I start out with keyNames and then I declare that type O must have the keys in the keyNames.

This is useful in the case when o is a big type definition and I want to have all the keys on a single line in source code rather than having to scroll.

But at the same time, I'd like to be notified by the compiler if I miss one key when declaring O, or if I misspell one, etc.

Upvotes: 0

Views: 192

Answers (1)

Max Burson
Max Burson

Reputation: 11

Record<KeyNames, unknown> will match types with at least the keys of KeyNames.

Upvotes: 1

Related Questions