Determine the tuple data type by analyzing a union of tuples using a single element as reference

Looking for a way to work with a union of tuples:

type TupleUnion = ["a", string] | ["b", number] | [Foo, Bar] // ...

In need of defining a function that can handle any type K extends TupleUnion[0], with the return type being inferred as the second element in the tuple:

function f<K extends TupleUnion[0]>(key: K): ValueFor<K>

How should I define

ValueFor<K extends TupleUnion[0]>
to get the desired outcome?

Answer №1

In order to filter a specific union member from the TupleUnion where the member is a tuple with a first element K, we can utilize the Extract utility type. Once filtered, we can then retrieve the second element of the extracted tuple.

declare function f<
  K extends TupleUnion[0]
>(key: K): Extract<TupleUnion, [K, any]>[1]

Check out this example in the Playground


Update:

To fix the issue mentioned in the comments.

type ValueFor<T, K> = T extends [any, any] 
  ? K extends T[0] 
    ? T[1]
    : never
  : never

declare function f<K extends TupleUnion[0]>(key: K): ValueFor<TupleUnion, K>;

Take a look at the corrected version on the Playground

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

Is there a Typescript function error that occurs when attempting to rename a key, stating it "could potentially be instantiated with a different subtype"?

I am currently working on a Mongoify type that accepts a type T, removes the id key, and replaces it with an _id key. type Mongoify<T extends {id: string}> = Omit<T, "id"> & { _id: ObjectId }; function fromMongo<T extends ...

What is the method for extracting children from a singular object in json-server rather than an array?

I am currently utilizing json-server as a mock-backend to fetch child data from a single object. The main table is called sentinel and the secondary table is named sensor https://i.sstatic.net/1BrRq.png https://i.sstatic.net/3lOVD.png It can be observ ...

Creating a List programatically in material-ui can be easily achieved by following these steps

I am attempting to create a contact view using the list component from Material-UI. My code is written in typescript, but I am struggling with setting up react and material-ui correctly. Any guidance would be greatly appreciated. export interface IConta ...

Identifying when an element is in or out of view using Next.js and TypeScript

I'm currently working on an app using Next and Typescript. The app features a navigation bar at the top of the screen, and I need it to change its style once it reaches a certain point in the view. I attempted to use jQuery for this purpose, but encou ...

What are the steps to expand the express object with TypeScript?

I am facing an issue where, after compiling a typescript project, the express import import {Request, Response} is not showing up. I am now attempting to use require, but I am unsure of how to extend the express object and utilize req and res. Any assistan ...

Encountering an issue with Typescript and SystemJS: Struggling to locate a

After developing a module, I decided to move it out of the app and into node_modules. However, I encountered an error error TS2307: Cannot find module 'bipartite-graph'.. In this case, bipartite-graph is actually my own module. Here is the conte ...

Utilize Typescript to inject types into a library

I have a code snippet that reads data from a JSON file and creates a type based on it, which is then used for further operations. import jsonData from './mydata.json' type CustomType = typeof jsonData .... This process ensures that the generate ...

Replace interface with a string

Is it possible to override an interface with a string in TypeScript? Consider this example: type RankList = "Manager" | "Staff" interface EmployeeList { id: string, name: string, department: string, rank: "Staff&q ...

My worker threads seem to be flying under the radar

Currently, I am working on implementing worker threads into my Node.js/Typescript application. I have made significant progress, but it appears that my worker threads are not being executed as expected. Despite adding loggers inside the function intended f ...

What steps can I take to ensure that the upper and left sections of a modal dialog remain accessible even when the size is reduced to the point of overflow?

One issue I'm facing is with a fixed-size modal dialog where part of the content gets cut off and becomes inaccessible when the window shrinks to cause an overflow. More specifically, when the window is narrowed horizontally, the left side is cut off ...

Creating a Docker Image for Node.Js Using Bazel

Reason Behind the Need I am diving into the Bazel world and struggling to find comprehensive references on constructing Docker images for Node.js. My focus lies on a Typescript-based Node.js application that relies on two other Typescript packages. My ul ...

Trigger refetchQueries post-execution of a mutation operation

In the past, I executed a mutation in a similar manner as shown below: export const useEditLocationName = () => { const [editFavoriteLocationName] = useEditFavoriteLocationNameMutation({ refetchQueries: [{ query: GetMyFavouritePlacesDocument}], ...

Angular causes HTML Dropdown to vanish once a null value is assigned

In my scenario, I have two variables named power and mainPower. Both of these variables essentially represent the same concept, with mainPower storing an ID of type Long in the backend, while power contains all attributes of this data transfer object. The ...

Tips on expanding properties for Material-UI components with Typescript?

My goal is to enhance the props of the Button component from Material-UI using typescript in order to pass additional props to its children. import { NavLink } from 'react-router-dom'; import { Button } from 'material-ui'; <Button ...

Providing properties to the main Vue.js components

An Issue I'm Facing I am currently attempting to pass a prop to my root constructor. To achieve this, I have been exploring the use of propsData, which I learned about from this resource: var appComponent = Vue.component('app', require(&ap ...

Utilizing a component from a different module

Currently working on Angular 4 and facing an issue with referencing a component from another module. In my EngagementModule, the setup is defined as below: import { NgModule } from '@angular/core'; // other imports... @NgModule({ imports: [ ...

The functionality of the Request interface appears to be malfunctioning

Hey there, I'm currently working on building an API using Express and TypeScript. My goal is to extend the Request object to include a user property. I've done some research on Google and found several posts on StackOverflow that explain how to d ...

How come the type checker is not throwing an error for this indexable type?

I recently delved into the Microsoft Typescript Handbook and found myself intrigued by the indexable types chapter. To gain a deeper understanding, I decided to experiment with the code provided. Strangely enough, upon running this particular piece of code ...

The expiration of the Gitlab CI/CD cache leads to the failure of the build process

I have an AWS CDK application in TypeScript and a simple GitLab CI/CD pipeline with 2 stages for deployment: image: node:latest stages: - dependencies - deploy dependencies: stage: dependencies only: refs: - master changes: - ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...