![](/img/trans.png)
[英]Ensure my function returns mutated object as instanceof the same class typescript?
[英]instanceof function parameter returns false in Typescript/Angular
我試圖找出如何獲取對象的類型(如果將其作為參數傳遞給我的函數)。
例如,您有以下代碼
getTypeOfAnimal(animal){
console.log(animal instanceof Cat)
console.log(animal instanceof Bear)
}
動物可以是貓或熊的實例。 從我的表單傳入的動物總是返回false(同樣,如果對象的結構似乎與貓或熊之一匹配)。
有沒有辦法正確獲取類型?
問題的根源是這條線
如果對象的結構似乎與貓或熊之一匹配
對象結構在這里無關緊要。 該instanceof
檢查是否使用的構造函數創建對象Cat
或Bear
,如new Cat()
(實際上如果同時延長Animal
那么instanceof Animal
是true
兩個)。
通常,TypeScript使用鴨子類型來解析接口是否與對象結構匹配,並且這是類似對象結構可以工作的地方。 但是instanceof
是JavaScript(因為是在運行時執行的),因此TypeScript不能再做更多了。 這就是為什么它不起作用的原因。
如果要處理層次結構中的類,則可以使用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
處理要縮小的結構類型時,可以使用自定義類型防護:
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));
如果某事物足夠“基本”可以滿足您的需要,這可以解決...
但是,總的來說,要當心不要過多地了解類型。 主要用例是縮小聯合類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.