代码之家  ›  专栏  ›  技术社区  ›  user944513

如何检查typescript+angular中变量的类型?

  •  1
  • user944513  · 技术社区  · 8 年前

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

    true false

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

    4 回复  |  直到 7 年前
        1
  •  6
  •   Bobby Titian Cernicova-Dragomir    7 年前

    接口在运行时被清除,因此在任何运行时调用中都不会有接口的跟踪。您可以使用类而不是接口(类在运行时存在并遵守 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 
        }
    }
    
        2
  •  4
  •   Florian Ludewig    8 年前

    typeof(variable); 所以在你的例子中: console.log(typeof(this.a));

        3
  •  2
  •   zerocewl    8 年前

    a instanceof Abc;
    

    另请参见: Class type check with typescript

        4
  •  0
  •   Pardeep Jain    8 年前

    所以代码在运行时没有意义。如果你这么做的话,它总会回来的 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

    推荐文章