Discovering the class type in TypeScript

In my TypeScript coding journey, I encountered a challenge in detecting a specific Class type. Despite its seeming simplicity, I found a lack of straightforward documentation on how to accomplish this task. Here is an example that illustrates the issue:

Class Car {}

Class Ford extends Car {}

Class Audi extends Car {}

let mustang = new Ford();
let a6 = new Audi();

// Given instances of Ford and Audi, how can I determine their types dynamically??
console.log(a6.getType()); // <--- looking for 'Audi' here
console.log(mustang.getType()); // <--- expecting 'Ford' as the output

I am exploring possibilities to identify the most specific version of Car (either Audi or Ford) in a generic manner. While acknowledging that "getType()" is not a built-in function, I am curious to know if there exist any simple solutions or alternative perspectives on tackling this problem.

Answer β„–1

At runtime, Typescript does not grant access to types. To achieve this, the traditional JavaScript method using class.constructor.name is necessary.

For example:

class Car {}

class Ford extends Car {}

class Audi extends Car {}

let mustang = new Ford();
let a6 = new Audi();

console.log(mustang.constructor.name)
console.log(a6.constructor.name)

JulienD's answer suggests an update..
To account for cases where the name and class name may differ, it is advisable to enhance the approach. Creating a getter function makes it more convenient than directly using this.constructor.name. For instance:

    class Car {
       carType: string = '';
       public get name(): string {
          return this.carType || this.constructor.name;
       }
    }

    class Ford extends Car {
        carType: string = 'Shelby';
    }

    class Audi extends Car {}

    let mustang = new Ford();
    let a6 = new Audi();

    console.log(mustang.name)
    console.log(a6.name)

Answer β„–2

By making changes to the classes, you can introduce a new property that is specifically defined in subclasses. Take this example:

class Vehicle {
  type: string = 'vehicle';
}

class Bike extends Vehicle {
  type = 'bike';
}

class Truck extends Vehicle {
  type = 'truck';
}

let mountainBike = new Bike();
let semiTruck = new Truck();

console.log(semiTruck.type); // <--- returns truck
console.log(mountainBike.type); // <--- returns bike

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

Tips for displaying dynamic images using the combination of the base URL and file name in an *ngFor loop

I have a base URL which is http://www.example.com, and the file names are coming from an API stored in the dataSource array as shown below: [ { "bid": "2", "bnam": "ChickenChilli", "adds": "nsnnsnw, nnsnsnsn", "pdap": " ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

Navigating Angular QueryList through loops

I am currently trying to gather all the images in my component and store them in an array. To achieve this, I am utilizing Angular's @ViewChildren which returns a QueryList of ElementRef: @ViewChildren('img', { read: ElementRef }) images: Q ...

Creating subclass mappings and defining subclasses dynamically using Typescript at runtime

I am puzzled by the structure of 3 classes: A, B, and C. Both B and C extend the abstract class A. abstract class A { public name: string; constructor(name: string) { this.name = name; } abstract getName(): string; } class B extends A { g ...

I'm looking to learn how to implement the delete method in an API using TypeScript. Can anyone help me out

I am seeking guidance on utilizing 'axios' within 'nuxt.js'. I have experimented with sample data, and I am particularly interested in learning how to utilize the 'axios' method within 'nuxt.js' using TypeScript. T ...

Choosing a value type within an interface or object declaration

Is it possible to extract a nested type object from an interface or parent type? interface IFake { button: { height: { dense: number; standard: number; }; }; otherStuff: string; } type Button = Pick<IFake, 'button'& ...

Next.js experiencing hydration error due to dynamic component

Having an issue with my RandomShape component, where it should display a random SVG shape each time the page is reloaded. However, I am encountering a hydration error on the client side. import React from "react"; import shapes, { getRandomShape ...

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 ...

What is the process for expanding types for a section element in Typescript?

When working with TypeScript, we define our component props types by extending a div like so: import { HTMLAttributes } from "react"; export interface IContainerProps extends HTMLAttributes<HTMLDivElement> { // Additional custom props for the c ...

Executing an AngularJS function using regular JavaScript code

I am currently working with AngularJS and Typescript. I have integrated an external library into my project and now I need to call an AngularJS method from that library, which is written in vanilla JavaScript. I tried following this example, but unfortunat ...

What's the trick to aligning the label on the material-ui text field to the right side?

I am working on a React project with an RTL layout using material-ui and typescript. I am struggling to align the label of a text field to the right. Can anyone help me with this? https://i.sstatic.net/UrkIF.jpg ...

Developing a custom React component library using Webpack and Typescript, however encountering issues with Webpack consistently bundling React

I'm currently in the process of developing an external component library using Webpack and TypeScript. Although it compiles without any issues, I encounter an error when attempting to use the library: Invalid hook call. Hooks can only be called ins ...

The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels. The data retrieved from my API is as ...

What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below? Below is the function I currently use to update ...

Is it possible to display Angular Material Slider after the label?

Searching through the Angular Material docks, I came across the Sliders feature. By default, the slider is displayed first, followed by its label like this: https://i.sstatic.net/C5LDj.png However, my goal is to have the text 'Auto Approve?' sh ...

Typescript: The original type cannot be indexed with a type-mapped type

I'm currently working on a class where I need to define a method that returns an object with keys based on the generic type inferred by the compiler. However, I've encountered an issue with the code snippet below. The compiler is indicating that ...

Do type declaration files for NPM packages have to be in the .d.ts format?

I believe it is feasible to include type declarations in any typescript file like '.d.ts', '.ts', or '.tsx'. However, I have observed that the type declaration files for most npm packages are .d.ts files. Is this a requireme ...

Organizing objects into arrays in Node.js

I have an array and I need to concatenate an object after the array. Here is my array: const users = [ {name: "Joe", age: 22}, {name: "Kevin", age: 24}, {name: "Peter", age: 21} ] And here is my object: ...

What method can be used to inherit the variable type of a class through its constructor

Currently, I am in the process of creating a validator class. Here's what it looks like: class Validator { private path: string; private data: unknown; constructor(path: string, data: string) { this.data = data; this.path = path; } ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...