【问题标题】:Test if var is of a union type in Typescript在 Typescript 中测试 var 是否属于联合类型
【发布时间】:2020-06-27 23:36:38
【问题描述】:

我想在一个测试函数中测试 var man 是否是 person 类型,但它确实输出了人和动物,那么正确的方法是什么?

    class Man {}
    class Woman {}
    class Cat {}
    class Dog {}
    type Person = Man | Woman;
    type Animal = Cat | Dog;

    function test(entity: Person | Animal) {
        if (entity as Person) {
            console.log('person')
        }
        if (entity as Animal) {
            console.log('animal')
        }
    }

    let man = new Man();

    test(man);

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    编译时类型会被删除,因此您想在运行时检查的任何内容都使用标准 javascript。删除类型后,您当前的代码只是:

    if (entity) {
      console.log('person')
    }
    

    所以你只是检查实体是否真实(不是null,不是undefined,不是0,不是空字符串等)

    相反,您可以使用 instanceof:

    if (entity instanceof Man || entity instanceof Woman) {
      console.log('person')
    }
    

    或者,如果这些类有一些独特的属性,你可以检查一下。

    class Man { isPerson = true }
    class Woman { isPerson = true }
    class Cat { isPerson = false }
    class Dog { isPerson = false }
    
    // ...
    if (entity.isPerson) {
      console.log('person')
    }
    

    【讨论】:

    • 我很遗憾他们没有为此添加功能:我想避免枚举所有子类型;)
    猜你喜欢
    • 1970-01-01
    • 2010-11-02
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    相关资源
    最近更新 更多