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

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)

它应该给truefalse

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)


zer*_*ewl 9

尝试“instanceof”或“is”:

a instanceof Abc;
Run Code Online (Sandbox Code Playgroud)

另请参阅: 使用打字稿进行类类型检查


flo*_*olu 7

只需typeof(variable); 在您的情况下使用即可:

console.log(typeof(this.a));
Run Code Online (Sandbox Code Playgroud)


小智 5

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

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