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

Determine the generic parameter of the output type by analyzing the resolved value of a data type within the function

I am looking to automatically determine the generic parameter of the return type by utilizing the resolved value of a type within the function. Consider the following: export type Context = any; export type Handler<T> = (ctx: Context) => Promise& ...

The type 'Requireable<string>' cannot be matched with the type 'Validator<"horizontal" | "vertical" | undefined>'

code import * as React from 'react'; import * as PropTypes from 'prop-types'; interface ILayoutProps { dir?: 'horizontal' | 'vertical' }; const Layout: React.FunctionComponent<ILayoutProps> = (props) => ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

Exploring the Depths of JSON Arrays within Typescript

I am faced with a challenge in extracting the value of the "id" from the following array of JSON data. The issue lies in the fact that the value is enclosed within double square brackets "[[" which are causing complications in retrieving the desired result ...

Leverage the Angular2 component property when initializing a jQuery function

I'm currently developing a web app with Angular 2 and utilizing jQuery autocomplete. When making requests to the remote server for completion data, I found that the server address is hardcoded in the autocomplete function. Even though I tried using co ...

Using the React UseEffect Hook allows for value updates to occur within the hook itself, but not within the main

I am currently utilizing a font-picker-react package to display fonts using the Google Font API. Whenever a new font is chosen from the dropdown, my goal is to update a field value accordingly. While the 'value' updates correctly within the ...

Create a conditional statement based on the properties of an object

In one of my Typescript projects, I am faced with the task of constructing a dynamic 'if' statement based on the data received from an object. The number of conditions in this 'if' statement should match the number of properties present ...

Angular 2 date validation rule for dd/mm/yyyy format in forms with reactive functionality

this.seedFundForm = this.fb.group({ multipleSource: this.fb.array([]), amount:[data.amount, Validators.compose([Validators.required, Validators.pattern('[0-9]*'), Validators.maxLength(10)])], date:[data.date, Validators.compose([Valid ...

While making changes, I was anticipating a "for-of" loop to be used instead of a "for" loop

There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...) loop. Consider this straightforward code snippet: this.filters['1','2','3'....]; for (let i = 0; i < this.filters.length; i+ ...

Adding to an existing array in SQLite by updating a column using Sequelize

My code includes a model definition for saving product data using Sequelize: This is how the Product model looks: import {Optional, Model, Sequelize, DataTypes } from 'sequelize'; /*This is the Product model used to save the data about products* ...

Tips for scrolling ion-items vertically to the bottom and top using arrow icons in Ionic 4

I'm developing an Ionic 4 app with Angular and looking to incorporate Up and Down Arrow buttons for vertical scrolling from top to bottom and vice versa. ...

The index signature for strings appears to be duplicated in this TypeScript file, causing an

I am attempting to create a type with an index signature in TypeScript. Here is the code snippet: export interface LoginState { account: { [userName: string]: string; [password: string]: string; }; } However, I ...

Can you identify the TypeScript type for an array containing various Angular components?

In my application, I have a diverse range of components that I would like to organize into an array. There are no restrictions on what types of components can be included in this array, as long as they are Angular components. What is the correct way to de ...

Creating an Angular 2 component that utilizes an interface within the constructor

If you have an interface named IData, and you want to develop an Angular 2 component that can accept any Class utilizing IData in its constructor, could this concept be implemented or is it off track? Your insights are greatly appreciated. ...

Choose an alternative following the start-up phase

I have been searching for solutions on various platforms, including Stack Overflow, but nothing seems to work for me. I am struggling with selecting the first option after initializing the box because currently it is choosing a blank option that is not eve ...

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

What is the reason behind a TypeScript compiler error being triggered by an 'if-else' statement, while a ternary operator construct that appears identical does not raise any errors?

My function is designed to either return a value of IDBValidKey or something that has been converted to IDBValidKey. When I use the ternary operator to write the function, it works fine. However, if I try to write it as an if-else statement, it causes a co ...

HashId plugin for Angular

Currently, I'm attempting to integrate into my Angular project built on the latest version. After discovering this definition file: // Type definitions for Hashids.js 1.x // Project: https://github.com/ivanakimov/hashids.node.js // Definitions by: ...

Navigating any object array in TypeScript and retrieving its properties

Consider the following JSON data object: var dataObjects = [ { "Name": "Date & Time", "Type": "Date", "Value": "2019-12-11" }, { "Name": "Activity", "Type": "String", ...

Ways to pass data to a different module component by utilizing BehaviourSubject

In multiple projects, I have used a particular approach to pass data from one component to another. However, in my current project, I am facing an issue with passing data from a parent component (in AppModule) to a sidebar component (in CoreModule) upon dr ...