本文介绍了打字稿:如何为联合类型中的枚举添加类型保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码给出错误:

  1. "instanceof"表达式的左侧必须为"any"类型,对象或类型参数.
  2. 类型'E |C'不可分配给'E'类型.不能将类型"C"分配给类型"E".
    enum E { FIRST = 1, SECOND = 2 };

    class C {
        value: E;

        constructor(arg: C | E) {
            if (arg instanceof C) { // 1.
                this.value = arg.value;
            } else {
               this.value = arg; // 2.
            }
        }
    }

    var a: C = new C(E.SECOND);
    console.log('a.value = ' + a.value);

    var b: C = new C(a);
    console.log('b.value = ' + b.value);

尽管存在错误,但代码似乎可以在 TypeScript游乐场,然后按预期操作.

Despite the errors the code seems to compile fine on TypeScript Playground and does the expected.

推荐答案

两个问题.

编译器中存在一个错误,即当联合类型的一个组成部分不是对象类型时,不允许在联合类型上使用 instanceof .这是固定的( https://github.com/Microsoft/TypeScript/issues/2775)

There's a bug in the compiler that instanceof isn't allowed on union types when one of its constituents isn't an object type. This is being fixed (https://github.com/Microsoft/TypeScript/issues/2775)

另一件事是, instanceof 不会导致 else 块中的缩小( https://github.com/Microsoft/TypeScript/issues/1719 ),因为未通过 instanceof 检查并不一定 表示对象与指定的接口不匹配.目前,这是设计使然",但我鼓励您发表评论,认为这种行为令人惊讶或不受欢迎(我当然愿意).

The other thing is that instanceof does not cause narrowing in the else block (https://github.com/Microsoft/TypeScript/issues/1719) because failing an instanceof check doesn't necessarily mean the object doesn't match the specified interface. This is currently "by design" but I'd encourage you to leave a comment that you find this behavior surprising or undesirable (I certainly do).

这篇关于打字稿:如何为联合类型中的枚举添加类型保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:21