could you please tell me how to check typeof of variable in typescript + 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) } }
It should give true
and false
https://stackblitz.com/edit/angular-jfargi?file=src/app/app.component.ts
Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.
TypeScript adds a typeof operator you can use in a type context to refer to the type of a variable or property: let s = "hello"; let n : typeof s ; let n: string. This isn't very useful for basic types, but combined with other type operators, you can use typeof to conveniently express many patterns.
To be more precise, Angular creates Type Check Blocks (TCBs) based on the component template. Basically, a Type Check Block is a block of TypeScript code which can be inlined into source files, and when type checked by the TypeScript compiler will give us information about any typing errors in template expressions.
Master Typescript : Learn Typescript from scratchVariable names can contain alphabets and numeric digits. They cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign. Variable names cannot begin with a digit.
Interfaces are erased at runtime so there will be no trace of the interface in any runtime call. You can either use a class instead of an interface (classes exist at runtime and obey 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 be true } }
Or you can do structural checking to see if the properties of Abc
are present at runtime in the object:
export class AppComponent { name = 'Angular 6'; a: Abc = { name: "sss" } constructor() { console.log('name' in this.a) // Will be true } }
just use typeof(variable);
so in your case:
console.log(typeof(this.a));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With