如何在TypeScript + Angular中检查变量类型?

27

请问在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


对于 true / false,您必须根据某个值进行检查。 - Mohd Tabish Baig
6个回答

36

接口在运行时会被擦除,因此在任何运行时调用中都不会留下接口的痕迹。你可以使用类代替接口(类存在于运行时并遵守 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 
    }
}

不必测试'name' in this.a,因为this.a遵循一个接口,可以这样做:const myInterface = this.a as MyInterface; console.log(myInterface.name) - Jose Alban
结构检查工作正常,但对于类的 instanceof 操作有点棘手。它们只在使用 new 关键字初始化变量时起作用。如果以对象形式初始化,则无法正常运行。 请参考: https://stackblitz.com/edit/angular-vz9oyw?file=src%2Fapp%2Fapp.component.ts - Neophyte

32

只需使用typeof(variable);即可。 所以在你的情况下:

console.log(typeof(this.a));

9

6

对于基本类型(例如字符串、数字等),您可以按照以下方式进行检查:

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


3

接口 仅在编译时存在,并在编译后被删除, 因此代码在运行时没有意义。如果您尝试,它将始终返回false

请看这里 -

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

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

实例演示

更多详细信息请参考以下链接:


1

试一下这个

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

1
仅有代码的回答几乎总是可以通过解释它们如何以及为什么工作来改进。 - Jason Aller
下次,我会尝试附上解释来回答问题。谢谢。 - Trilok Singh
1
目前,您可以只需[编辑]您的帖子以添加一些说明。 - double-beep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接