Obtaining the identifier of a generic type parameter in Typescript

Is there a method in TypeScript to retrieve the name of a generic type parameter?

Consider the following method:

getName<T>(): string {
   .... implement using some operator or technique 
}

You can use it like this:

class MyClass{
}


getName<MyClass>(); ///=> should return 'MyClass'

I attempted to utilize https://www.npmjs.com/package/ts-nameof, but it was unsuccessful.

Trying to do this:

const name = nameof<T>();

results in an error.

Are there any alternative methods for achieving this outcome?

Answer №1

Unfortunately, TypeScript alone does not have the capability to support generic types since it ultimately compiles down to JavaScript, which lacks that feature. As a result, using syntax like getName<MyClass>(); in TypeScript will be compiled to getName();, resulting in the same output without any parameter differentiation.

To work around this limitation, you can either use a code generator to produce additional code or modify your function by adding a parameter, as shown below:

function getName<T extends new (...args: any[]) => any>(clazz: T): string {
  return clazz.name;
}

class MyClass{
}

getName(MyClass);

It's important to note that this solution only applies to classes that exist at runtime and cannot be applied universally across all scenarios.

Answer №2

To effectively utilize TypeScript transform plugins, it is crucial to ensure that the necessary prerequisites are properly set up.

Transform plugins such as ts-nameof require specific setup steps due to their reliance on the transform compiler, ttypescript.

Here's what needs to be done:

1. Installation of ttypescript and ts-nameof:

npm i ttypescript ts-nameof @types/ts-nameof -D

2. Adding ts-nameof to the plugins array in your tsconfig.json:

{
  "compilerOptions": {
    "noEmitOnError": true,
    "target": "ES2020",
    "plugins": [{ "transform": "ts-nameof", "type": "raw" }],
  }
}

3. Updating the path for the tsdk to the location of ttypescript in your vscode user settings:

"typescript.tsdk": "node_modules/ttypescript/lib" // for intellisense

4. Executing with npx

npx ttsc

After completing these steps, utilizing the following code:

 const name = nameof<MyClass>();

will result in:

const name = "MyClass";

For reference: ts-nameof-example

Original documentation sources:

Answer №3

One strategy involves creating a class type interface specifically for the function parameter:

export declare interface ClassType<T> {
    new (...args: any[]): T;
}
class NewClass {
}
function getClassName<TClass>(classType: ClassType<TClass>): string {
    return classType.name;
}

This approach requires passing the class name as an argument to retrieve it:

let myClassName = getClassName(NewClass);

The limitation is that you cannot apply this method to a generic that originates from a data type.

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

Potential absence of the object has been detected after performing object verification

I encountered an issue with the following error message: Object is possibly 'undefined'.ts(2532) This is what my configuration looks like: export interface IDataColumns { name: string; label: string; display: string; empty: boolean; fi ...

Updating the style of different input elements using Angular's dynamic CSS properties

I am seeking guidance on the proper method for achieving a specific functionality. I have a set of buttons, and I would like the opacity of a button to increase when it is pressed. Here is the approach I have taken so far, but I have doubts about its eff ...

I encountered the error message "The property you are trying to access does not exist on the type 'never'" while attempting to retrieve JSON data from the API response

Every time I attempt to access the fields in items such as id or title, an error pops up saying Property does not exist on type 'never'. Interestingly, when I log the data using console.log(response.data), everything seems to be working fine. I ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...

Error in TypeScript: The property 'data' is not found within type '{ children?: ReactNode; }'. (ts2339)

Question I am currently working on a project using BlitzJS. While fetching some data, I encountered a Typescript issue that says: Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339) import { BlitzPage } from &q ...

What is the best way to save the output of an asynchronous function into a class attribute?

Currently, I am attempting to retrieve HTML content from a webpage by utilizing a class equipped with a single asynchronous method. This process involves Typescript 3.4.3 and request-promise 4.2.4. import * as rp from 'request-promise'; class H ...

Is it feasible to implement early-return typeguards in Typescript?

There are instances where I find myself needing to perform type checks on variables within a function before proceeding further. Personally, I try to minimize nesting in my code and often utilize early-return statements to keep the main functionality of a ...

Do Angular FormControl objects have the capability to accept input values of various types, or are they limited to TypeScript primitive types?

When creating a reactive form in Angular using FormControl objects in a FormGroup, I encountered an issue. While passing primitive arguments as values for an HTML input select control works fine, when passing an object of a self-defined class, the value in ...

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Error: Attempting to add types to an object returned from the .map function in JSX Element

When attempting to include the item type in the object returned from the .map function, I encountered a JSX error. I tried specifying item: JSX.Element as the Item type, but this didn't resolve the issue. Can someone provide clarity on this matter? Th ...

Encountering an issue while attempting to input a URL into the Iframe Src in Angular 2

When I click to dynamically add a URL into an iframe src, I encounter the following error message: Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'SafeValue%20must%20use%20%5Bproperty%5D' To ensure the safety of the ...

What is the best way to categorize a collection of objects within a string based on their distinct properties?

I am working with an array of hundreds of objects in JavaScript, each object follows this structure : object1 = { objectClass : Car, parentClass : Vehicle, name : BMW } object2 = { objectClass : Bicycle, parentClass : Vehicle, name : Giant } object3 = { ob ...

Ways to reload a page in Angular using routerLink and ID

I am working on an Angular application that involves navigation using routerlinks. My goal is to navigate to a specific user page by ID if the page is already open and meets certain conditions. In my .component.ts file, I have the following code snippet: ...

What steps should I follow to ensure that TypeScript is aware of the specific proptypes I am implementing?

Is there a way to instruct TypeScript on the prop types that a component is receiving? For example, if multiple is set to true, I would like TypeScript to expect that selectValue will be an array of strings. If it's not present, then TypeScript should ...

Utilize a Typescript library within a separate Typescript library

I have a TypeScript library on GitHub that I want to install using npm install --save git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f38362b1d15c3f4">[email protected]</a>:User/mylib.git into my targ ...

Inference in Typescript - Detecting unknown key in an object

I am struggling to implement type inference from a props object that is passed to a component and then used in a render function. While I can retrieve the keys of the object correctly, all types are being interpreted as unknown. I need some assistance in f ...

Tips for accessing the value from a subscription within a function in Ionic 3

I am working on a function that retrieves a JSON file from a specific URL. The issue I am facing is that I am trying to access a random object from this data within the file, stored in this.data. However, when I attempt to console.log(this.data) outside of ...

Leveraging the Nest JS Validation Pipe in combination with the class-transformer to retrieve kebab-case query parameters

Can someone help me with using the Nest JS Validation Pipe to automatically transform and validate my GET Request Query Params? For example: {{url}}/path?param-one=value&param-two=value In my app.module.ts, I have included the following code to impl ...

Arranging the output of a Typescript project

I'm currently advocating for Typescript to be implemented in our web application. Can anyone provide insight on the best method for structuring Javascript output files? Should they be excluded from source control? And when it comes to testing, is it p ...

What is the best way to retrieve data from MySQL for the current month using JavaScript?

I need to retrieve only the records from the current month within a table. Here is the code snippet: let startDate = req.body.startDate let endDate = req.body.endDate let result = await caseRegistration.findByDate({ p ...