Tips for utilizing generics to determine the data type of a property by its name

I am seeking a method to determine the type of any property within a class or a type.

For instance, if I had the classes PersonClass and PersonType, and I wanted to retrieve the type of the nationalId property, I could achieve this using the following code:

class PersonClass{
    name: string
    nationalId: number
}

type PersonalType={
    name: string
    nationalId: string
}

type GetNationalIdType<T> = T extends {nationalId: infer U} ? U : never;
var nId3: GetNationalIdType<PersonClass>
var nId4: GetNationalIdType<PersonalType>

This code works well, where nId3 is of type number and nId4 is of type string. However, if I want to retrieve the type of any property without knowing its name beforehand, I attempted the following:

// type GetProp<T, K> = T extends {[key: K]: infer U} ? U : never;
type GetProp<T, K extends string> = T extends {[key: K]: infer U} ? U : never;

var nId1: GetProp<PersonClass, "nationalId">
var nId2: GetProp<PersonalType, "nationalId">

Upon running the above code, I encountered the following results:

https://i.sstatic.net/hElpU.png

https://i.sstatic.net/eN5mv.png

Answer №1

If you're looking for information on lookup types, check out this link. In TypeScript, if T is an object type and K represents one of its keys (or a union of keys), then T[K] refers to the type of the value associated with that key:

var nId1: PersonClass["nationalId"]; 
var nId2: PersonalType["nationalId"];

If you need to define a function like GetProp, it can be done simply without conditional types:

type GetProp<T, K extends keyof T> = T[K];

Alternatively, if you want to handle cases where K may not necessarily match with keyof T:

type GetProp<T, K extends keyof any> = K extends keyof T ? T[K] : never;

For those interested in using infer and conditional types, a mapped type with Record might be needed:

type GetProp<T, K extends keyof any> = T extends Record<K, infer V> ? V : never;

However, the straightforward lookup type method is usually the recommended approach. Best of luck!

Answer №2

To achieve this, you will need to utilize the mapped type syntax in conjunction with conditional types:

type RetrieveProperty<T, K extends string> = T extends {[property in K]: infer Value} ? Value : never;

However, it seems like what you really require is a type query:

var id1: EmployeeClass["employeeId"]
var id2: PersonalType["personnelId"]

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 display multiple items on a single page using the Ant Design (NG-Zorro) carousel component?

Hey there, I'm looking for a way to display multiple items per page using the ant design (NG-Zorro) carousel. I found some information on their website here: What I'm aiming for is to have something like this - Multiple Items If you have any i ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

One potential solution for fixing the error in GetRepository of TypeORM is to check for undefined properties before attempting to access them. This error typically occurs when trying to read properties of an undefined

[Nest] 171 - 08/31/2022, 8:35:42 PM ERROR [ExceptionHandler] Cannot read properties of undefined (reading 'getRepository') tenant-node | TypeError: Cannot read properties of undefined (reading 'getRepository') tenant-node | at Instance ...

Assigning namespaces to a property of classes in typescript: A step-by-step guide

As I work on adding a declaration file to a TypeScript package, I encounter some syntax that looks like this: const Sequelize = require('Sequelize'); //... class Application { Sequelize = Sequelize; } To address this, I created a file named ...

Display different icons in an Angular application based on the value received from an API in real

My goal was to create a dynamic form that displays icons for the fields I have created. Here is a snapshot of my UI screen showing the field explorer with the list coming from an API. https://i.sstatic.net/4Ye9G.png I need to place an icon in front of ea ...

How might the issue of update activation affecting lazy loading in an Angular PWA app specifically manifest itself?

I am looking for a way to trigger an update activation in my Angular PWA app. I came across a note in the documentation from the official Angular website (https://angular.io/guide/service-worker-communications) that says: "Doing this could break lazy-load ...

Encountering an endless loop within a data rest API in a React application

Currently, I am in the process of learning React and attempting to utilize the Poke API with my application. Unfortunately, I seem to have run into an infinite loop issue and I am feeling quite lost in terms of troubleshooting it. Below is a snippet of my ...

Retrieve a specific subset of a union based on the class in a generic function

This question shares similarities with another post I made, but this time focusing on using classes instead of plain objects. class Exception1 extends Error { constructor(message: string, public arg1: string) { super(message); } } class Ex ...

Add a feature to a functional component that is enclosed with React.forwardRef

Within my codebase, there exists a component that is wrapped with React.forwardRef and serves as a compound component. One challenge I encountered was how to preserve the functionality of Form.Item = FormItem; while still having the Form component fun ...

What steps can I take to ensure that Visual Studio replaces my JavaScript file during the TypeScript build process?

In my development process using Visual Studio to work on my TypeScript project, I have encountered an issue with the build process. I have a build.ts file that links to all of my other TS files and compiles them into one app.js file along with an associate ...

What is the best way to create a React text box that exclusively accepts numeric values or remains empty, and automatically displays the number keypad on mobile devices?

While there are numerous similar questions on StackOverflow, none of them fully address all of my requirements in a single solution. Any assistance would be greatly appreciated. The Issue at Hand Within my React application, I am in need of a text box tha ...

A Typescript type that verifies whether a provided key, when used in an object, resolves to an array

I have a theoretical question regarding creating an input type that checks if a specific enum key, when passed as a key to an object, resolves to an array. Allow me to illustrate this with an example: enum FormKeys { x = "x", y = "y&q ...

The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows: import { createServer } from 'http'; import type { NextApiHandler } from 'next'; import type { __ApiPreviewProps } ...

Struggling to transmit data to material dialog in Angular2+

I am facing an issue with my Material Dialog not working properly. Can anyone point out what I might be missing? product-thumbnail.ts I will use this to trigger the dialog export class ProductThumbnailComponent implements OnInit { @Input() product: Pr ...

Ionic: Implementing a clear text field function when the ion-back-button is clicked

So I've created a feature where users can scan product barcodes using BarcodeScanner. Once the barcode is scanned, the product ID appears in a text field and is then sent to another page where an API call is made to display product details. On this pr ...

Typescript Routing Issue - This call does not match any overloads

Need assistance with redirecting to a sign-up page upon button click. Currently encountering a 'no overload matches this call' error in TypeScript. Have tried researching the issue online, but it's quite broad, and being new to Typescript ma ...

Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with two arrays: interface IFirst{ name: string; age: number } interface ISecond { nickName: string; lastName: string; } myFirstArray: IFirst[]; mySecondArray: ISe ...

Having trouble integrating NEXT AUTH with Firebase due to an error: "Cannot import statement outside

Let's take a look at our firebase configuration file: import { getFirestore } from "firebase/firestore"; export const firebaseConfig = { apiKey: process.env.FIREBASE_API_KEY, authDomain: process.env.FIREBASE_AUTH_DOMAIN, projectId: pr ...

I'm curious about why the value of my variable in service.ts keeps changing whenever the page is refreshed?

Below is my Angular service.ts file code. It is used to store the login status. import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) e ...

All-encompassing NextJS App router with a focus on Internationalization

I am currently working with a folder structure that includes an optional catch-all feature. The issue I am facing is that the page does not change when the URL is altered to include ""/"" or ""/about-us"". It consistently remains on the ...