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

新手上路,请多包涵

你能告诉我如何在 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

原文由 user944513 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 399
2 个回答

接口在运行时被擦除,因此在任何运行时调用中都不会出现接口的痕迹。您可以使用类而不是接口(类在运行时存在并遵守 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
    }
}

原文由 Titian Cernicova-Dragomir 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

原文由 octavian09 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进