如何检查打字稿+角度变量的类型?

时间:2018-07-05 11:37:35

标签: angular typescript

能否请您告诉我如何检查打字稿+ 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) 
  }
}

应该给truefalse

https://stackblitz.com/edit/angular-jfargi?file=src/app/app.component.ts

6 个答案:

答案 0 :(得分:6)

在运行时会删除接口,因此在任何运行时调用中都不会跟踪该接口。您可以使用类而不是接口(类在运行时存在,并遵守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 
    }
}

答案 1 :(得分:3)

只需使用typeof(variable); 因此,根据您的情况:console.log(typeof(this.a));

答案 2 :(得分:2)

尝试“ instanceof”或“ is”:

foreach i in 0 ... 9 {
        //some logic
}

另请参阅: Class type check with typescript

答案 3 :(得分:0)

  

接口 仅在编译时存在,并且在编译后被删除,因此代码在运行时毫无意义。如果这样做,它将始终返回false

在这里看看-

constructor(){
    console.log(typeof(this.a), '---');
    console.log(this.instanceOfA(this.a)); 
  }

  instanceOfA(object: any): object is ABc {
    return 'member' in object;
  }

Working Example

有关更多详细信息,请参见此处-

答案 4 :(得分:0)

对于基本类型(字符串,数字等),您可以像这样检查:

if( typeof(your_variable) === 'string' ) { ... }

答案 5 :(得分:0)

尝试

  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...
    }