【问题标题】:Cannot use instanceof on union type in typescript [duplicate]无法在打字稿中的联合类型上使用 instanceof [重复]
【发布时间】:2020-02-27 07:27:33
【问题描述】:

我得到错误:

TS2358:“instanceof”表达式的左侧必须是 type 'any',对象类型或类型参数。

编译以下代码时:

const animal: Tiger | Monkey | Goat = fetchAnimal();
if (!animal instanceof Tiger && !animal instanceof Monkey) {
    alert('It is safe to touch the animal');
}

【问题讨论】:

    标签: typescript compiler-errors union instanceof


    【解决方案1】:

    原来我需要添加括号,然后它起作用了:

    if (!(animal instanceof Tiger) && !(animal instanceof Monkey)) {
        alert('It is safe to touch the animal');
    }
    

    【讨论】:

    • 是的。如果没有(),则为(!animal) instanceof Monkey,最终为true instanceof Monkeyfalse instanceof Monkey。 :-) 一元运算符的优先级通常非常
    猜你喜欢
    • 2020-05-21
    • 1970-01-01
    • 2020-11-30
    • 2022-06-13
    • 1970-01-01
    • 2018-12-06
    • 2021-10-18
    • 2021-06-27
    • 2023-02-13
    相关资源
    最近更新 更多