Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforcing object keys from in TypeScript

Let's say I have

type Panel = 'store' | 'logs'

I want to create an object that has key => ReactChild with key being only the values in Panel

const object = {
    store: StoreComponent,
    logs: LogsComponent
}

How do I define the type of object here?

like image 234
Kousha Avatar asked Oct 26 '25 00:10

Kousha


1 Answers

The predefined mapped type Record is what you are looking for. This will take a union of keys and create an object type where each property has the type specified as the second parameter to the type:

type Panel = 'store' | 'logs'

const object:Record<Panel, ReactChild> = {
    store: StoreComponent,
    logs: LogsComponent
}
like image 142
Titian Cernicova-Dragomir Avatar answered Oct 27 '25 14:10

Titian Cernicova-Dragomir