Reputation: 12729
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
Upvotes: 32
Views: 219179
Reputation: 1353
try this
console.log(typeof (this.specialProviderSelected));
we can check type of variable like as string, number, object etc
if((typeof (this.specialProviderSelected)) === 'string') {
action here...
}
if((typeof (this.specialProviderSelected)) === 'number') {
action here...
}
if((typeof (this.specialProviderSelected)) === 'object') {
action here...
}
Upvotes: 1
Reputation: 159
For basic types (string, number, etc) you can check like this:
if( typeof(your_variable) === 'string' ) { ... }
Upvotes: 6
Reputation: 6002
just use typeof(variable);
so in your case:
console.log(typeof(this.a));
Upvotes: 36
Reputation: 249676
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
}
}
Upvotes: 38
Reputation: 86740
Interfaces only exist at compile-time and are removed after compilation, so that code makes no sense at run-time. If you try so it will always return
false
.
Have 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;
}
For more in details refer here -
Upvotes: 3
Reputation: 12804
Try 'instanceof' or 'is':
a instanceof Abc;
See also: Class type check with typescript
Upvotes: 9