Why can't I do instanceof on a union?

ⅰ亾dé卋堺 提交于 2021-01-26 17:35:17

问题


It won't allow an instanceof in this case - why?

public assign(color: string | ColorProperty | RgbProperty | RgbColor): void {
    super.assign(color);

    if (color instanceof ColorProperty) {

ps - I LOVE unions!!!


回答1:


It seems that the instanceof keyword must have a type any included in the union in order to use it within a function.
My guess would be that the compiler needs to handle the case where all of your type guards return false - and therefore the type is inferred as any.

function assign(_color: any | string | ColorProperty | RbgProperty) {
    if (_color instanceof ColorProperty) {
    }
    // else may not be a string | ColorProperty | RbgProperty
}



回答2:


It's not quite correct to say that any has to be present in the union. This works as well.

class Foo { } 
class Bar { }

var x: Foo | Bar = new Foo();
if (x instanceof Foo) {
    // this is ok
}

However, this doesn't work, even though there's no union.

var n: number = 123;
if (n instanceof Foo) {
    // compile error
}

The problem is stated in the compiler error.

The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.

So it seems when a union contains any, you're always allowed to treat the values as if they were any, meaning there are no compile-time restrictions. Otherwise, the compiler only allows operations which are allowed to be applied to any of the individual types.



来源:https://stackoverflow.com/questions/28975200/why-cant-i-do-instanceof-on-a-union

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!