Is there a way to dynamically select the right type from a list of types, like a "type map," by passing a variable as component props? I've been trying to implement this concept called "Conditional Types" in TypeScript, but couldn't find a solution in the documentation.
Here's a simplified example:
type Queue1 = {};
type Queue2 = {};
type Queue3 = {};
// ... other possible types
type QueueTypes = {
'Queue1': Queue1,
'Queue2': Queue2,
'Queue3': Queue3
// ...
}
interface Props {
queueType: keyof QueueTypes;
}
let props: Props = {queueType: 'Queue2'}
// Type 'any' cannot be used as an index type
type selectedQueueType = QueueTypes[props.queueType]
Despite hours of searching, I haven't found the perfect solution yet. Am I approaching this problem with TypeScript incorrectly? Any guidance would be greatly appreciated.
View the code on the playground
Update: I have a generic react component (table) that needs to support various types of resources (Queue1, Queue2, etc). Since the resource type is dynamic and provided as a string, I need to convert/cast it to an existing TypeScript type. Building on my initial playground, the solution could resemble this:
interface Queue1 { q: 1 }
interface Queue2 { q: 2 }
interface Queue3 { q: 3 }
type QueueTypes = {
'Queue1': Queue1,
'Queue2': Queue2,
'Queue3': Queue3
}
type Props = { [K in keyof QueueTypes]: { queueType: K } }[keyof QueueTypes]
let props: Props = { queueType: 'Queue2' }
// <ResourceTable<QueueTypes[typeof props.queueType]>>