[英]how to check type of variable in typescript +angular?
你能告訴我如何在 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)
}
}
它應該給true
和false
https://stackblitz.com/edit/angular-jfargi?file=src/app/app.component.ts
接口在運行時被擦除,因此在任何運行時調用中都不會有接口的蹤跡。 您可以使用類而不是接口(類在運行時存在並遵守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
}
}
或者,您可以進行結構檢查以查看Abc
的屬性在運行時是否存在於對象中:
export class AppComponent {
name = 'Angular 6';
a: Abc = { name: "sss" }
constructor() {
console.log('name' in this.a) // Will be true
}
}
只需使用typeof(variable);
所以在你的情況下:
console.log(typeof(this.a));
對於基本類型(字符串、數字等),您可以這樣檢查:
if( typeof(your_variable) === 'string' ) { ... }
接口只在編譯時存在,編譯后被刪除,所以代碼在運行時沒有意義。 如果您嘗試這樣做,它將始終返回
false
。
看這里——
constructor(){
console.log(typeof(this.a), '---');
console.log(this.instanceOfA(this.a));
}
instanceOfA(object: any): object is ABc {
return 'member' in object;
}
有關詳細信息,請參閱此處 -
嘗試這個
console.log(typeof (this.specialProviderSelected));
我們可以檢查變量的類型,如字符串、數字、對象等
if((typeof (this.specialProviderSelected)) === 'string') {
action here...
}
if((typeof (this.specialProviderSelected)) === 'number') {
action here...
}
if((typeof (this.specialProviderSelected)) === 'object') {
action here...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.