简体   繁体   English

instanceof函数参数在Typescript / Angular中返回false

[英]instanceof function parameter returns false in Typescript/Angular

I'm trying to find out how to get the type of an Object if it was passed as a parameter in my function. 我试图找出如何获取对象的类型(如果将其作为参数传递给我的函数)。

For example you have following code 例如,您有以下代码

getTypeOfAnimal(animal){
   console.log(animal instanceof Cat)
   console.log(animal instanceof Bear)
}

animal could be either an instanceof a Cat or a Bear. 动物可以是猫或熊的实例。 The animal passed in from my form always returns false (also if the Object's structure seems to match one of a Cat or a Bear). 从我的表单传入的动物总是返回false(同样,如果对象的结构似乎与猫或熊之一匹配)。

Is there a way to get the type properly? 有没有办法正确获取类型?

The root of the problem is this line 问题的根源是这条线

also if the Object's structure seems to match one of a Cat or a Bear 如果对象的结构似乎与猫或熊之一匹配

The object structure won't matter here. 对象结构在这里无关紧要。 The instanceof checks whether the object was created using a constructor of Cat or Bear , eg new Cat() (and actually if both extend Animal then the instanceof Animal would be true for both). instanceof检查是否使用的构造函数创建对象CatBear ,如new Cat() (实际上如果同时延长Animal那么instanceof Animaltrue两个)。

Normally TypeScript uses duck typing to resolve whether the interface is matching the object structure and this is where the similar object structure could work. 通常,TypeScript使用鸭子类型来解析接口是否与对象结构匹配,并且这是类似对象结构可以工作的地方。 However instanceof is JavaScript (because is executed in the runtime), so there is no much more TypeScript can do there. 但是instanceof是JavaScript(因为是在运行时执行的),因此TypeScript不能再做更多了。 That is why it does not work as you might have expected. 这就是为什么它不起作用的原因。

If you are dealing with classes in a hierarchy, you can use instanceof : 如果要处理层次结构中的类,则可以使用instanceof

class Animal {
    name: string;
}

class Cat extends Animal {
    purrs: boolean;
}

class Bear extends Animal {
    growls: boolean;
}


const animal = new Cat();
console.log(animal instanceof Cat); // true
console.log(animal instanceof Bear); // false

When dealing with structural types that you want to narrow, you can use a custom type guard: 处理要缩小的结构类型时,可以使用自定义类型防护:

const structuralBear = {
    name: 'Paddington',
    growls: false
};

console.log(structuralBear instanceof Cat); // false
console.log(structuralBear instanceof Bear); // false

function isBeary(obj: any): obj is Bear {
    console.log(typeof obj.growls);
    return (typeof obj.name === 'string' && typeof obj.growls === 'boolean');
}

console.log(isBeary(structuralBear));

This works out if something is "beary" enough for your needs... 如果某事物足够“基本”可以满足您的需要,这可以解决...

On the whole, though, beware of needing to know too much about types in this way. 但是,总的来说,要当心不要过多地了解类型。 The main use case is to narrow a union type. 主要用例是缩小联合类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM