【问题标题】:How can I use instanceof inside a custom type guard in typescript?如何在打字稿的自定义类型保护中使用 instanceof?
【发布时间】:2022-11-02 18:40:40
【问题描述】:

我正在尝试使用 instanceof 创建自定义类型保护,但奇怪的是它在 else 子句中没有按预期工作

这是一个带有相关游乐场链接的示例: Playground Link

class Person {}

class Animal {}

const isPerson = (obj: Person | Animal): obj is Person => obj instanceof Person;
const isAnimal = (obj: Person | Animal): obj is Animal => obj instanceof Animal;

const test: Person | Animal = new Person();

if(isAnimal(test)){
  test; // const test: Animal
}
else {
  test; // const test: never

}

我希望在 else 子句中 test 的类型为 Person,但它的类型为 never... 为什么?

我知道我也可以直接使用instanceof,但我更希望有一个更简洁的函数,就像那些创建的那样

【问题讨论】:

    标签: typescript typeguards narrowing


    【解决方案1】:

    Typescript 非常聪明,它会看到您的测试变量是 Person 类型。

    因为你写了:const test: Person | Animal = new Person();

    以及为什么它说never,因为测试将never 转到else 语句。

    【讨论】:

    • 不,实际上,按照流程它总是会传递到else。 vighnesh153 是对的
    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 2021-03-25
    • 1970-01-01
    • 2017-05-18
    • 2020-12-24
    • 2016-11-12
    • 2019-03-03
    • 2020-08-02
    相关资源
    最近更新 更多