Ways to access the different variable types within a class?

Looking to retrieve the types of specific variables within a class. Example:

class CustomPerson {
    name: string = "";
    age: number = 0;
    ID?: number = undefined;
}
getVariableType(CustomPerson, "name") => string
getVariableType(CustomPerson, "age") => number
getVariableType(CustomPerson, "ID") => number | undefined

Prior attempts utilized Object.keys(new CustomPerson()) along with typeof (object as any)[key].

However, this method is limited to default variables of new CustomPerson(), resulting in inability to accurately determine type for ID (returns undefined instead of number | undefined).

Answer №1

To create a custom utility type for this scenario, you can utilize the built-in Pick utility type in TypeScript. This allows you to narrow down an object type to a specific property and then access that property's type using square bracket notation.

For instance, consider the following example with the PropType utility type:

class SampleObject {
    name: string = "";
    age: number = 0;
    ID?: number = undefined;
}

type PropType<T, P extends keyof T> = Pick<T, P>[P]

type NameType = PropType<SampleObject, "name">; // string
type AgeType = PropType<SampleObject, "age">; // number
type IdType = PropType<SampleObject, "ID">; // number | undefined

TypeScript Playground Link

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 process for sending JSON data in a file to a django rest api?

Currently, I am using Angular on the front-end and Django Rest on the back-end. I have encountered a scenario where I need to create a complex model. Despite considering other simpler solutions, I believe that using JSON to pass the files can streamline th ...

What is the process for designing a mapping type that involves two enums?

I need a solution to connect these two types and create mappings: type MappedEnum<T extends string, A extends string, B extends string> = { [key in T]: {[key in A]: B}; [key in T]: {[key in B]: A}; }; enum Greek { ALPHA = 'A', BET ...

Utilizing symbols as a keyof type: A simple guide

Let's consider the following: type Bar = keyof Collection<string> In this scenario, Bar denotes the type of keys present in the Collection object, such as insert or remove: const x: Bar = 'insert'; ✅ But wait, the Collection also c ...

Bidirectional enumeration in TypeScript

I am working with an enum defined as: enum MyEnum { key1 = 'val1' key2 = 'val2' } However, I am unsure how to create a SomeType implementation that fulfills the following requirements: Function: const myFunction = (param: SomeT ...

A guide on specifying the data type for functions that receive input from React Child components in TypeScript

Currently, I am faced with the task of determining the appropriate type for a function that I have created in a Parent Component to retrieve data from my Child Component. Initially, I resorted to using type: any as a solution, although it was not the corr ...

The headers in the Angular HttpClient Response Object do not show up in the network tab of browsers or when using PostMan

Here is the function that makes a POST call to the server: submitData(credential){ credential = JSON.stringify(credential); return this._http.post("http://localhost:8080/login",credential,{observe: 'response'}); } In this section ...

How can I modify my Axios Post request to receive a 201 status code in order to successfully save the data?

I am facing an issue when attempting to make a POST request locally with Axios on my NodeJS front-end app to my .NET core local server. The server returns a 204 status code and the axios request returns a pending promise. How can I change this to achieve a ...

Exploring the integration of Jest with TypeScript

I'm seeking guidance on how to set up TypeScript with Jest. I've scoured numerous resources but haven't found a solution that works for me. Below is my jest.config.js: module.exports = { roots: [ '<rootDir>' ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

What is causing my React-Testing Library queries to not work at all?

In my current project, I am using Jest along with Testing-Library to create UI unit tests. One issue that I encountered was that the components were not rendering on the DOM. After some investigation, I found that the main culprit was a component called & ...

There is an implicit 'any' type error binding element 'currency' in Graphql React Typescript

I am facing an issue with my code. I want to use the EXCHANGE_RATES in renderedExchangeRates, but I am receiving an error message saying "Error Message: Binding element 'currency' implicitly has an 'any' type." I understand that this is ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Using Jasmine to simulate an if/else statement in Angular/Typescript unit testing

After making a minor change to an existing function, it has been flagged as new code during our quality checks. This means I need to create a unit test specifically for the new 4 lines of code. The challenge is that there was never a unit test in place for ...

Exploring the possibilities of ZMQ_XPUB_MANUAL in action with zeromq.js

I'm currently in the process of setting up a pub/sub broker using ZeroMQ, and I want to ensure that clients are only able to subscribe to authorized prefixes. While researching this topic, I came across a helpful tutorial that discusses achieving a si ...

Conditioning types for uninitialized objects

Is there a way to create a conditional type that can determine if an object is empty? For instance: function test<T>(a: T): T extends {} ? string : never { return null } let o1: {} let o2: { fox? } let o3: { fox } test(o1) ...

Exploring TypeAhead functionality in Reactjs 18

I have encountered an issue while using react-bootstrap-typeahead version 5.1.8. The problem arises when I try to utilize the typeahead feature, as it displays an error related to 'name'. Below is my code snippet: import { Typeahead } from " ...

Can I leverage getStaticProps and getStaticPaths within a page component that employs dynamic routing without prior knowledge of the IDs?

I have created a fully static site generation (SSG) app where the backend cannot be accessed during build time. All the data is specific to user permissions, so I cannot specify paths in the getStaticPaths method required for dynamic routed components us ...

Verify the rendering process in the ForwardRef's render method

I have implemented the code exactly as provided in the example from https://material-ui.com/components/bottom-navigation/: // code in app.tsx: import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Bo ...

In JavaScript, loop through an array of arrays and combine them using the concat

If I have an array like [["a", "b"], ["c", "d"]], is there a way to iterate, reduce, map, or join this array in order to get the desired output of ["ac", "ad", "bc", "bd"]? What if the array is structured as [["a", "b"], ["c", "d"], ["e", "f"]]; how can we ...

The comparison between StrictNullChecks and Union Types in terms of syntax usage

Understanding StrictNullChecks in TypeScript Traditionally, null and undefined have been valid first class type citizens in JavaScript. TypeScript formerly did not enforce this, meaning you couldn't specify a variable to potentially be null or unde ...