use*_*513 6 typescript angular
你能告诉我如何检查打字稿+ angular中变量的typeof吗?
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)
}
}
Run Code Online (Sandbox Code Playgroud)
它应该给true和false
https://stackblitz.com/edit/angular-jfargi?file=src/app/app.component.ts
Tit*_*mir 10
接口在运行时会被擦除,因此在任何运行时调用中都不会跟踪该接口。您可以使用类而不是接口(类在运行时存在并且服从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
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以进行结构检查以查看Abc对象的属性是否在运行时存在:
export class AppComponent {
name = 'Angular 6';
a: Abc = { name: "sss" }
constructor() {
console.log('name' in this.a) // Will be true
}
}
Run Code Online (Sandbox Code Playgroud)
只需typeof(variable);
在您的情况下使用即可:
console.log(typeof(this.a));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33547 次 |
| 最近记录: |