Type determined by the variable's condition

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]>>

Answer №1

A Record is a specialized object type where the keys are represented by K and the values by T. In other words, using keyof Record is the same as using K, while Record[K] is equivalent to T.

type QueueTypes: Record<string, Queue1 | Queue2 | Queue3> = {
    'Queue1': Queue1,
    'Queue2': Queue2,
    'Queue2': Queue3
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing Caching in Angular 5 Services

Searching for the best way to implement Angular services has led me here. The Service: const url = 'http://127.0.0.1:8000/api/brands/' @Injectable() export class BrandService { private brands:Observable<Array<Brand>>; constru ...

What is the method to access the information within the observer?

When I receive the data from the observer in the console, here is what I see: https://i.stack.imgur.com/dVzwu.png However, I am only interested in extracting this specific data from each item on the list: https://i.stack.imgur.com/g8oHL.png To extract ...

Error: Undefined Property in Angular 2 ViewChild Declaration

Exploring a simple example where the childMethod is called within the child component from the parent component using the @ViewChild() decorator. However, encountering an issue where the ViewChild variable remains undefined. Sample Child Component Code: ...

Setting up AngularJS 1.5.x to function seamlessly with SystemJS and TypeScript

I'm looking to keep all my code in AngularJS 1.x while also preparing it for an easy upgrade to AngularJS 2 in the future. To align my code with Angular 2 standards, I am interested in using TypeScript and SystemJS in version 1.5.x initially. Is ther ...

Encountering a Typescript issue while trying to access two distinct values dynamically from within a single object

Currently, I'm developing a component library and facing an issue with a TypeScript error: An Element implicitly has an 'any' type due to the expression of type 'levelTypes | semanticTypes' being unable to index type '{ level1 ...

Is there a way to seamlessly transition between different Angular components without having to refresh the entire webpage?

I'm currently working on implementing a navigation bar that allows users to switch between three components without having the navbar reload. The goal is for only the new component to load when the user clicks on a different section of the navbar, kee ...

Error message in CodeSandBox with Angular: TypeError - The function html2canvas_1.default is not defined or recognized

Attempting to convert a basic html table into a PDF format within my project has resulted in unexpected errors when using CodeSandbox: ERROR TypeError: html2canvas_1.default is not a function at AppComponent.downloadPDF (https://3d3bh.csb.app/src/app/a ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

The validators in the FormControl are inconsistently functioning, showing up where they shouldn't and sometimes failing to work where

I am currently developing a dynamic form in Angular that allows users to request any number of parts, generating rows of input fields for each part. Each part has specific required fields, some of which should only accept numbers. I have implemented valid ...

Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on? for (let i = 0; i < Number(height); i++) { for (let j = 0; j < Number(width); j++ ...

When using TypeScript, the reducer function may not be recognized, causing the type to display as 'any

I am a beginner in Typescript and we are implementing hooks in our React application. We have a shared thunk action creator that triggers one of the actions. appSlice.ts type ThunkOptions = { method: number, api_url: string, body: any | null } ...

Is it possible to assign a type conditionally depending on the value of a boolean?

While grappling with this issue, the title question arose in my mind: How can I handle the situation where the library function getResponse returns { a: number } for Android phones and { b: number } for iOS phones? The code snippet below initially led to ...

Shifting attention to an angular 6 form field

I am developing an application in Angular which involves creating, reading, updating, and deleting user information. I have a requirement for the username to be unique and need to display an error message if it is not unique, while also focusing on the use ...

What steps can be taken to resolve the error message "Module '../home/featuredRooms' cannot be found, or its corresponding type declarations"?

Upon deploying my site to Netlify or Vercel, I encountered a strange error. The project runs smoothly on my computer but seems to have issues when deployed. I am using TypeScript with Next.js and even attempted renaming folders to lowercase. Feel free to ...

What is the best way to refresh the properties in an object?

I am working with a custom type object defined as follows: export interface IPupilFilter { Fullname: string; Gender: string; ClassType: number; Language: number; Class: number; ClassNumber: number; Phone: string; Movement: string; } public ...

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

Ways to convert a string into a Date object without using moment.js

I am facing a challenge with 2 dates that are stored in the following format: "04.12.2019, 09:35" // Today "05.12.2019, 12:50" // Another date I need to compare these dates to determine if they have passed or are yet to come. My initial approach was to ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...

What functionality does the --use-npm flag serve in the create-next-app command?

When starting a new NextJS project using the CLI, there's an option to use --use-npm when running the command npx create-next-app. If you run the command without any arguments (in interactive mode), this choice isn't provided. In the documentati ...

Displaying search results in various Angular components

On my home page (homePageComponent), I have a search feature. When the user clicks on the search button, they are redirected to a different page called the search list page (searchListComponent). Within the searchListComponent, there is another component c ...