kuceb
kuceb

Reputation: 18089

Typescript object with generic keys and regular keys?

I have the following type:

type MyKeys = 'foo' | 'bar' | 'baz'

I want to define a type that has keys of type MyKeys, but also extends it with more keys, like this:

type FooType = {
  [key in MyKeys]: boolean
  quux: boolean   // <--- Error: '}' expected.ts(1005)
}

How can I use both generic keys and explicit key names?

Upvotes: 0

Views: 174

Answers (1)

kuceb
kuceb

Reputation: 18089

You can use an Intersection Type:

type FooType = {[key in MyKeys]: boolean} & {
  quux: boolean
}

or as mentioned by @jcalz, you can also use Record<>:

Record<MyKeys | 'quux', boolean>

that will equivalent to:

enter image description here

Upvotes: 2

Related Questions