簡體   English   中英

如何檢查打字稿+角度中的變量類型?

[英]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) 
  }
}

它應該給truefalse

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' ) { ... }

嘗試“instanceof”或“is”:

a instanceof Abc;

另請參閱: 使用打字稿檢查類類型

接口只在編譯時存在,編譯后被刪除,所以代碼在運行時沒有意義。 如果您嘗試這樣做,它將始終返回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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM