Accessing properties in TypeScript using an index that is determined by another property within the same interface

Allow me to illustrate my query with an example rather than simply using words:

interface Y {
    x: number,
    y: string
}

interface PairValue<T> {
    key: keyof T,
    value: T[this['key']]
}

const pairValue: PairValue<Y> = {
    key: 'x',
    value: 'Issue! This should be a number'
};

My objective is to have the type of value determined by the value of key. In other words, if key is x, then I want the type of value to match the type of Y[x], which is number. However, at present, the type of value is string | number, resulting from the union of all value types in Y.

Is it possible to accomplish this using the current features available in TypeScript?

Answer №1

You cannot achieve this directly, as an additional type parameter is required.

interface Y {
    a: number,
    b: string
}

interface KeyValue<T, K extends keyof T> {
    key: K,
    value: T[this['key']] // or T[K]
}

const keyValue: KeyValue<Y, 'a'> = {
    key: 'a',
    value: 0
};

To streamline the process and avoid redundant typing of the property name, a function can be utilized for assistance. A fi function is needed that returns a function, since Typescript currently does not support partial type argument inference

function newX<T>() {
    return function <K extends keyof T>(p: Y<T, K>) {
        return p;
    }
}

let xy = newX<Y>()({ key: 'a', value:0})

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

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

Exploring TypeScript and React: Redefining Type Definitions for Libraries

As I transition from JSX to TSX, a challenge has arisen: My use of a third-party library (React-Filepond) This library has multiple prop types The provided types for this library were created by an individual not affiliated with the original library (@ty ...

Updating an array by adding or removing items

I am attempting to create a method for deleting and adding items to an array, but I need easy-to-use delete and add methods since I am unfamiliar with TypeScript. export class NgForComponent implements OnInit { Numbers: number[]; constructor() { ...

Ways to utilize the useRef method within the useContext hook while implementing Typescript

Struggling to incorporate useRef into my global Next.js useContext function while utilizing TypeScript. Attempted approach and encountered errors: interface tripAttributes{ tripTitle: string } const initialTripState: tripAttributes = { tripTitle ...

Issue with Angular Material: Default selection not being applied in mat-select component

When I have a mat-select with options defined as objects in an array, I am facing an issue where the default selected value is not being set when the page renders. In my TypeScript file, I have: public options2 = [ {"id": 1, "name": "a"}, {"id": 2 ...

Utilizing objects as values with `react-hook-form`

About the Issue I'm facing an issue with a component that utilizes an object as its value. My goal is to integrate this component with react-hook-form The challenge arises when react-hook-form considers my object as a nested form control Background ...

Encountering an error when trying to set data in a Firestore document with a customized JavaScript object: "Invalid data provided for function DocumentReference.set()"

For my initial project, I need help in identifying where the issue lies. Firstly, I have a function that adds data to Firebase: addpost() { let newposts = new Posts( this.addForm.value ) this.postsservice.addPosts(newposts); } Ne ...

The TypeScript error "File 'XXX' is not recognized as a module" is preventing successful compilation

Is there a way to import a module from an external file into another TS file? Even after following the steps, when I tried to do so in VSCode, it gave me an error saying that the file 'XXX' is not a module: Here's the error I encountered I ...

How can TypeScript leverage the power of JavaScript libraries?

As a newcomer to TypeScript, I apologize if this question seems simplistic. My goal is to incorporate JavaScript libraries into a .ts file while utilizing node.js for running my program via the console. In my previous experience with JavaScript, I utilize ...

Checkbox selections persist when navigating between pages

I am currently working with Angular 9 and I have a list of checkboxes that need to default to true when displaying certain data. If one of these checkboxes is unchecked, it should trigger the display of specific information. The issue I am facing is that o ...

Attempting to utilize a default import to invoke an expression that does not have a call signature is not

I am currently experimenting with using https://github.com/arnaudbenard/redux-mock-store in conjunction with TypeScript. I have gone ahead and installed @types/redux-mock-store which includes the necessary export default createStore statement. In my attem ...

Issue with Typescript npm script including compilation and nodemon issue

After exploring various SO links, I tried to find a way to simultaneously run both tsc -w and nodemon app.js using a single command. The link I referred to is: How do I execute typescript watch and running server at the same time? Working on a node.js pr ...

Tips for programmatically focusing on a v-textarea using Vuetify and TypeScript

It feels impossible right now, I've attempted some unconventional methods like: (this.refs.vtextarea as any).textarea.focus() ((this.refs.vtextarea as Vue).$el as HTMLElement).focus() and so on... Javascript source code is quite complex for me to ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

Unable to send JSON data from server to client following a successful file upload operation

I'm currently working on a project that involves NodeJS, Express, JQuery, and Typescript. The issue I'm facing is related to uploading a file from the front end, which is successful. However, I'm encountering difficulties in returning a JSON ...

What is the process for obtaining the result of an asynchronous function triggered by an event in HTML?

I am currently working on an Angular application where I have a button that triggers a click event. The method being called is asynchronous and involves subscribing to an observable. My goal is to call player.start() only after the listItems.getData() meth ...

Tips for effectively utilizing react-test-renderer/shallow in a TypeScript environment

Looking to utilize react-test-renderer/shallow for testing my react component. However, when I try to import ShallowRenderer from 'react-test-renderer/shallow'; tsc throws an error stating that 'Module '"/Users/dulin/workspace/react-t ...

Implement dynamic routerLink binding with Angular 11

Having a value containing routerLink and queryParams, I am attempting to bind it in the HTML. anchorValue : string = `<a [routerLink]="['../category/new ']" [queryParams]="{ query: 'category' }" routerLinkActive = ...

What are the TypeScript type definitions for the "package.json" configuration file?

What is the most efficient method for typing the content of the "package.json" file in TypeScript? import { promises as fs } from 'fs'; export function loadManifest(): Promise<any> { const manifestPath = `${PROJECT_DIR}/package.json`; ...

Using Angular BehaviorSubject in different routed components always results in null values when accessing with .getValue or .subscribe

I am facing an issue in my Angular application where the JSON object saved in the service is not being retrieved properly. When I navigate to another page, the BehaviorSubject .getValue() always returns empty. I have tried using .subscribe but without succ ...