Combining tuples with their corresponding data types

Trying to define a new type:

type Union = [1, "one"] | [1, "first"] | [2, "two"]

type GetTuple<T, U> = Extract<T, [U, ...unknown[]]>;

type ObjectFromUnion<T extends Union[0] = Union[0]> = {
  number: T,
  word: ??
}

Looking to utilize the ObjectFromUnion type as props for a React component without specifying a generic type, letting it infer based on the values of number and word props.

Expected behavior:

<Component number={1} word=/* "one" or "first" */ /> 
<Component number={2} word=/* "two" */ /> 
<Component word="one" number=/* {1} */ /> 
<Component word="first" number=/* {1} */ /> 
<Component word="two" number=/* {2} */ /> 

Answer №1

If you want to achieve this, consider leveraging mapped types.

type Choices = [1, "one"] | [1, "first"] | [2, "two"];
type ChosenType = {[Key in Choices as Key[0]]: Key[1]};

function ShowComponent<Index extends keyof ChosenType>(properties: {number: Index; word: ChosenType[Index]}) {
    return <div>{properties.number}: {properties.word}</div>
}

Check out this live example on the playground.

Once you input the number, you'll witness narrowing and autocomplete suggestions for the word.

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

What is the best way to add query parameters to router.push without cluttering the URL?

In my current project, I am using NextJS 13 with TypeScript but not utilizing the app router. I am facing an issue while trying to pass data over router.push to a dynamically routed page in Next.js without compromising the clarity of the URL. router.push({ ...

Show the user's chosen name in place of their actual identity during a chat

I'm facing an issue where I want to show the user's friendly name in a conversation, but it looks like the Message resource only returns the identity string as the message author. I attempted to retrieve the conversation participants, generate a ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

Error with tsc rootDir due to Docker's installation of yarn in root directory

I am encountering a problem with my node project which serves a simple "hello world" server. Everything runs smoothly when I run it locally, but when I try to run it inside Docker, a /opt/yarn-v1.21.1 folder is created which leads to a rootDir error: erro ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

Using arrays as props in React with Typescript

In my code, I have a Navbar component that contains a NavDropdown component. I want to pass an array as a prop to the NavDropdown component in order to display its dropdown items. The array will be structured like this: DropDownItems: [ { ...

Utilizing a package from your local computer

Due to my current circumstances, I am unable to utilize the npm publish command to release a package on the internet and subsequently use npm install. I also have no intention of publishing it on a remote server like nexus. Is there a method available to ...

What is causing Angular to consistently display the first object in the array on the child view, while the child .ts file correctly prints information from a different object?

Once a card of any object is clicked, the information of that specific object will be printed to the console. However, the child view will only display the details of the first object in the array it retrieves from. All pages are included below. A visual e ...

When defining a stripe in TypeScript using process.env.STRIPE_SECRET_KEY, an error of "string | undefined" is encountered

Every time I attempt to create a new stripe object, I encounter the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string& ...

Error code 2532 occurs when trying to access an object using square brackets in TypeScript

Encountered the ts error: Object is possibly 'undefined'.(2532) issue while trying to access the value of a field within an object, where the object key corresponds to a value in an Enum. Below is a concise example to showcase this problem: en ...

Implementing handleRequest as an asynchronous function within the passportjs guard

@Injectable() export class RefreshAuthGuard extends JwtAuthGuard { constructor( private readonly jwtService: JwtService, ) { super(); } public handleRequest(err: any, user: any, info: Error, ctx: any): any { if (err ...

Creating a function in typescript that returns a type based on the input parameter

type A = { aa: string; bb: number; }; type G = { <T extends keyof A>(a: T): A[T]; <T1 extends keyof A, T2 extends keyof A>(a: T1, b: T2): [A[T1], A[T2]]; // ... }; const g = {} as G; const x = g('aa'); //string const y = g ...

Utilizing the Pub/Sub architecture to integrate the kafka-node library within Node Js

Utilizing the kafka-node module in my NodeJs Microservise project, I am aiming to implement a Pub/Sub (publisher and subscriber) design pattern within the Functional programming paradigm. producer.js const client = new kafka.KafkaClient({ kafkaHost: ...

Can callback argument types be contingent on certain conditions? For example, could argument 0 be null if argument 1 is a string?

I am attempting to implement conditional type logic for the parameter types of a callback function. In this scenario, the first argument represents the value while the second argument could be an error message. type CallbackWithoutError = (value: string, ...

Utilizing TypeScript to define the parameter of a method within a generic interface by extracting a value from the generic type

In search of defining a versatile interface that can manage any Data type, I came up with an idea. This interface includes a dataKey property which simply holds a value of keyof Data. Additionally, it features a handler function where the parameter type sh ...

Top method for managing dates in TypeScript interfaces received from the server

After encountering the issue detailed in Dates in a Typescript interface are actually strings when inspected I faced a challenge while defining a TypeScript interface for a response from a server API, particularly with a Date parameter. The data arrived a ...

Experiencing difficulty accessing the response header in Angular 16 due to CORS restrictions

When attempting to retrieve the response header from my post call, I am encountering difficulties as it appears there are "no headers" or I may be doing something incorrectly. On the backend, I am utilizing ASP.NET Core. Below is a basic outline of my API ...

Displaying an error message following the dynamic retrieval of the input field's value

How can I display an error message when a specific field with a value of 0 is not filled out in my Angular reactive forms? In my form, I have added a dropdown which is mandatory and I have implemented validators to ensure it is required. The validator work ...

The not-null constraint is violated in the "id" column because of a null value when using Sequelize Typescript

My Database Setup Journey Recently, I embarked on a database adventure where I decided to use Sequelize-Typescript to assist me with all the heavy lifting in terms of database operations. The first step was creating a table called uma_tbl_users, and here ...

After utilizing the d3-scale function to declare an object, my developer visual suddenly ceases to function

Upon completing a section of a Power BI tutorial, the developer encountered a visual that displayed nothing but a blank page (despite running correctly). Unable to pinpoint the issue, debugging was initiated. The following test code snippet for debugging w ...