Getting the Class name in Typescript

How can you retrieve the class name from within a Class in typescript?

For instance, consider this code snippet:

export class SomeRandomName extends AbstractSomething<SomeType> implements OnDestroy {

  className = 'SomeRandomName';

Is there a method to automatically set the className variable to the name of the class SomeRandomName?

Appreciate any insights.

Answer №1

Here is a straightforward solution:

class NewClass extends AbstractAnother<AnotherType> implements OnInit {
      getLabel() {
        return (this as any).constructor.name;
      }
}

Answer №2

An ES6 class in TypeScript works just like a regular ES6 class. To retrieve the name of the class as a string, you can use the .constructor.name property.

class Bar {}

const bar = new Bar();
console.log(bar.constructor.name); // Bar

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

TypeScript Error: The Object prototype must be an Object or null, it cannot be undefined

Just recently, I delved into TypeScript and attempted to convert a JavaScript code to TypeScript while incorporating more object-oriented features. However, I encountered an issue when trying to execute it with cmd using the ns-node command. private usern ...

In order to access the localStorage from a different component, a page refresh is required as it is

UPDATE: Just to clarify, this question is NOT duplicate of how to retrieve the value from localstorage. My scenario is unique and the issue lies with Angular itself rather than localStorage. I am currently developing an Angular7 application. In one of my ...

The Observable<T> generic type must be provided with one type argument

I encountered the following 3 errors while working with the Angular 2 (TypeScript) code below. Can you provide suggestions on how to resolve them? import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { NgModule, Com ...

How should one begin a new NativeScript-Vue project while implementing Typescript support in the most effective manner?

Is it possible to incorporate Typescript into Vue instance methods? I found guidance on the blog page of nativescript-vue.org. Whenever I initiate a new nativescript-vue project using vue init nativescript-vue/vue-cli-template <project-name>, some w ...

Angular reactive form validation ensures user inputs are accurate and complete before submitting

Within my reactive Angular form, I have a specific field that requires validation. In my service class, I am currently utilizing the default Validators.required function provided by Angular in the following code snippet: Countrycode: new FormControl(&apos ...

Removing a directory from GitHub with the help of octokit/rest

I am attempting to utilize octokit/rest in order to programmatically remove a directory. Below is the code I am using: import {Octokit as Github} from '@octokit/rest'; const githubToken = "read from vault"; // Functions for retrieving current c ...

Categorize items based on their defined attributes using Typescript

[origin object array and expect object array ][1] origin object array: 0: amount: 100000000000000000000 feeTier: 0.3 price: 00000 priceDecimal: 0000 status: "unknown" tokenXAddr: "0x*********" tokenXSymbol: "USDC" tokenYAddr: ...

Here's a unique rewritten version: "Achieving a looping carousel with autoplay in Angular 2+ using with

Could someone provide recommendations for an image carousel that is compatible with angular 8? I would also like to know how to customize the images inside the carousel specifically for small devices. Thank you in advance! ...

Dropdown with no selected option

Having some trouble with the p-dropdown element in Angular5 and primeng library. Specifically, when dealing with a large entity called Consignment that has multiple fields, I notice that the selected values on several p-dropdown elements (in this case, the ...

Define a distinct routing parameter that can be accessed through the ActivatedRoute instance

While working on setting up a router in my application, I encountered the need to define a query parameter that must be retrievable through the ActivatedRoute for compatibility reasons. Recently, I had to create some new sub-routes that do not follow the s ...

What is the best way to run tests on customized Material-UI components with withStyles using react-testing-library?

Creating a test with a styled Material-UI component using react-testing-library in typescript has proven to be challenging, particularly when trying to access the internal functions of the component for mocking and assertions. Form.tsx export const style ...

Issue with page reload in Angular 8 when URL contains a dot

When the URL contains a dot(.) and we attempt to reload the page using the browser's reload function, the following error occurs: The resource you are seeking has been deleted, its name has been changed, or it is currently unavailable. We prefer not ...

The header code in Angular 6 does not get triggered when working with the router

After successfully validating the username and password, I perform the following action: this.router.navigate(['./home']); Each page includes a header with the following content: <ng-container *ngIf='isAuthenticated'> <li c ...

Angular request accessing CoinMarketCap API

Currently, I am immersing myself in the world of the latest CoinMarketCap API and navigating through the waters of data. The Node.js example below demonstrates how to make a request. But how can I achieve the same in Angular? Any tips or suggestions would ...

Angular NodeJS API failing to retrieve search data

I have implemented a search feature using Angular and Node.js. After testing it with Postman, everything seemed to be working fine. However, when I tried connecting it to the front-end Angular application, I encountered an error. Failed to load resource: t ...

CORS policy preventing successful POST request

Every time I send a request to my API, Chrome blocks it due to CORS. To fix this issue on my Firebase Cloud Function, I included the line response.set('Access-Control-Allow-Origin','*'); (xxxxxx in the axios get hides the request URL) e ...

Utilizing AngularFirestore to fetch a reference to a document within a collection and associate it with a specific class model

I'm exploring ways to merge two Firestore collections that are connected through a reference field. These are the two collections in question: https://i.sstatic.net/ARGHs.png In my userstory template, I aim to showcase the displayName of the referen ...

Webpack and React.js: Additional loaders might be required to manage the output generated by these loaders

An error occurred while parsing the module in ./productFlow/index.tsx at line 3, column 12. The file was processed with the following loaders: * ./node_modules/awesome-typescript-loader/dist/entry.js. It seems like an additional loader may be needed to h ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

What is the best way to access dependencies that are externally defined in the root package.json file?

I'm unsure of the appropriate terminology for this concept. If you have the correct TERM to share or a reference for me to learn more about it, please provide the link. Currently, I am examining our extensive package.json file for various projects. ...