how to check type of variable in typescript +angular?
just use typeof(variable);
so in your case:
console.log(typeof(this.a));
Try 'instanceof' or 'is':
a instanceof Abc;
See also: Class type check with typescript
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
}
}