what is the best way to determine the variable type in typescript and angular?

How can I determine the type of a variable in TypeScript with Angular?

import { Component } from '@angular/core';

interface Abc {
  name : string
}
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  a:Abc= {
    name:"sss"
  }

  constructor(){
    console.log(typeof this.a)
   // console.log(this.a instanceof Abc) 
  }
}

This code snippet should provide results of true and false

Visit StackBlitz for more details.

Answer №1

Runtime erases interfaces, leaving no trace of them in function calls. To work around this, you can opt for using classes instead of interfaces since classes are present at runtime and adhere to instanceof

class Abc {
    private noLiterals: undefined;
    constructor(public name: string) { }
}
@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    name = 'Angular 6';
    a: Abc = new Abc( "sss")

    constructor() {
        console.log(this.a instanceof Abc) // Will return true 
    }
}

Alternatively, you can perform structural checks to verify if the properties of Abc exist at runtime in the object:

export class AppComponent {
    name = 'Angular 6';
    a: Abc = { name: "sss" }

    constructor() {
        console.log('name' in this.a) // Will return true 
    }
}

Answer №2

To check the type of a variable, simply utilize typeof(variableName);. In your situation, it would look like this:

console.log(typeof(exampleVariable));

Answer №3

Use 'instanceof' or 'is':

a instanceof Abc;

For more information, check out: Class type check with typescript

Answer №4

When dealing with primitive data types such as strings or numbers, you can verify the type like so:

if( typeof(your_variable) === 'string' ) { ... }

Answer №5

At compile-time, interfaces are present but they are removed after compilation, which means the code will not have any effect at run-time and will always return false if you try to execute it.

If you're curious, take a look here -

constructor(){
    console.log(typeof(this.a), '---');
    console.log(this.instanceOfA(this.a)); 
  }

  instanceOfA(object: any): object is ABc {
    return 'member' in object;
  }

See a Working Example

To dive deeper into this topic, check out -

Answer №6

give this a shot

  console.log(typeof (this.specialProviderSelected));

testing out how to determine the type of a variable, such as string, number, or object, among others

  if((typeof (this.specialProviderSelected)) === 'string') {
     reacting accordingly...
    }
   if((typeof (this.specialProviderSelected))  === 'number') {
     reacting accordingly...
    }
    if((typeof (this.specialProviderSelected))  === 'object') {
     reacting accordingly...
    }

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

Is there an automatic bottom padding feature?

Currently, I am facing a challenge in fitting the loader into the container without it being overridden by the browser. Using padding-bottom is not an ideal solution as it results in the loader appearing un-resized and unprofessional. Any suggestions or co ...

The custom form input in Angular2 is throwing an error because it is trying to access the property 'name' of an

Upon switching to the latest Angular version 2 final, I encountered the following error Uncaught TypeError: Cannot read property 'name' of undefined This is my customized input import { Component, EventEmitter, Provider, forwardRef } from &a ...

A more efficient method for defining and utilizing string enums in Typescript

enum PAGES { HOME = 'HOME', CONTACT = 'CONTACT', } export const links: { [key: string]: string } = { [PAGES.HOME]: '/home', [PAGES.CONTACT]: '/contact', }; export function getLink(page: string) { return B ...

Formcontrol is not functioning properly with invalid input

I am attempting to style an input field with a FormControl using the :invalid pseudo-class. Here is my code snippet: scss input:invalid { background-color: red; } html <input type="text" [formControl]="NameCtrl"> Unfortunate ...

"Choose one specific type in Typescript, there are no in-b

Need help returning an object as a fetch response with either the property "data" or "mes": { data: Data } | { mes: ErrMessage } Having trouble with TypeScript complaining about this object, let's call it props: if (prop.mes) return // Property &a ...

shared interfaces in a complete javascript application

In the past, I have typically used different languages for front-end and back-end development. But now, I want to explore the benefits of using JavaScript/TypeScript on both sides so that I can have key data models defined in one central location for both ...

Angular elements nested within each other are causing the ExpressionChangedAfterItHasBeenCheckedError

After conducting thorough research on this issue, I am now uncertain whether it is a bug or an error in my implementation. The problem arises with an element that utilizes a service to retrieve data and then passes it on to a child element. However, upon ...

Angular ensures that the script is loaded only once

Here's a piece of code I wrote: ngOnInit() { this.loadScript('./assets/js/jquery.dataTables.min.js'); this.loadScript('./assets/js/datatable.js'); this.loadScript('./assets/js/common.js'); } Every time the page ...

Creating a function to target a specific HTML class in Angular can be achieved by utilizing Angular

Can a function be created for the entire class instead of adding it to each individual line? In this case, I have a class called "dropdown-item" for each link with this class, and I want them all to have the same function. <li class="nav-item dr ...

Learn how to utilize ng2-file-upload in Angular for uploading .ply files effortlessly!

I'm currently working on uploading various files using ng2-file-upload. I've been successful in uploading different file types like png and jpg, but I'm facing an issue with the .ply file extension. Can someone guide me on how to upload a fi ...

In Typescript, inheritance of classes with differing constructor signatures is not permitted

While working on implementing a commandBus, I encountered an issue when trying to register command types with command handlers for mapping incoming commands. My approach was to use register(handler : typeof Handler, command : typeof Command), but it result ...

Encountering an issue stating that Object literal can solely specify recognized properties through Wagmi

Currently, I am experimenting with TypeScript following a wagmi example found at this link: https://wagmi.sh/examples/contract-write. Here is the code snippet I am working with: export function Write() { const { config } = usePrepareContractWrite({ a ...

Error: In Angular and Typescript, the function this.$resource is not recognized

I keep encountering a TypeError: this.$resource is not a function. Below is the code snippet causing the issue: export class DataAccessService implements IDataAccessService { static $inject = ["$resource"]; constructor(private $resource: ng ...

The Angular-Chart.js chart fails to display when data is automatically inserted

I came across this sample code at https://stackblitz.com/edit/angular-chartjs-multiple-charts and tried using it. Everything was working well with static data, but when I attempted to push data retrieved from the Firebase Realtime Database into the chart, ...

Utilizing a TypeScript getter or local variable to reference a service variable within an Angular component

Suppose you have an array of objects stored in a service export class DataService { private _dataSources : Array<DataSource> contructor(private callerService: CallerService){ this._dataSources = this.callerService.getDataSources(); // fetc ...

Overlap occurs when Angular Material 2 cards are used in conjunction with flex-layout

I'm currently working on implementing Angular Material 2 cards with flex-layout to dynamically change the number of columns displayed as the browser is resized. My goal is to achieve a layout similar to how Google Keep works. <div *ngIf="condition ...

Struggling to grasp the process of incorporating OAuth into both a REST API and a Single Page Application

I am currently working on integrating my SPA, DjangoRestframework, and auth0. My understanding is that the user registration process, as well as logging in and out, are all handled by Angular. Here are some key questions I need assistance with: 1. Aft ...

Is it possible to eliminate a parameter when the generic type 'T' is equal to 'void'?

In the code snippet below, I am attempting to specify the type of the resolve callback. Initially: Generic Approach export interface PromiseHandler<T> { resolve: (result: T) => void // <----- My query is about this line reject: (error: a ...

Ways to manage an interactive pricing structure chart in Angular?

In my application, users can choose from four different types of plans that are retrieved from the backend. Once a plan is selected, they are directed to a payment page. The pricing table page can be revisited, and if a user has already purchased a plan, t ...

Mapping objects in Typescript to create a union of objects

I have been working on some TypeScript code and I seem to be having trouble getting it to work as expected. It would be greatly appreciated if someone could help me understand what I'm doing wrong or suggest a different approach. Let's assume I ...