考慮我們有 2 個類Animal和Dog. 這里Dog的類是從類繼承的Animal。
我需要檢查這個物件的型別
我怎樣才能做到這一點
class Animal {}
class Dog extends Animal {}
//This obj can have both classes
const mixedObj: Animal | Dog = new Dog();
//---> here When i compare mixedObj with Animal class i need to get `false` but `true` is returned
console.log(mixedObj instanceof Animal);// returns: `true`
console.log(mixedObj instanceof Dog);// returns: true
有沒有其他方法可以解決這個問題...?
uj5u.com熱心網友回復:
從根本上說,您是在詢問 的運行時值mixedObj,這是 JavaScript 的事情,而不是 TypeScript 的事情。
instanceof Animal將true適用于在其原型鏈中具有任何位置的任何物件Animal.prototype(通常因為它是由Animal建構式直接或間接創建的[例如,通過Dog])。如果要查看是否mixedObj包含 a Dog,特別是,而不是Animal,則需要查看constructor屬性:
class Animal {}
class Dog extends Animal {}
//This obj can have either class
const mixedObj/*: Animal | Dog*/ = new Dog();
console.log(mixedObj.constructor === Animal);// returns: `false`
console.log(mixedObj.constructor === Dog);// returns: `true`
游樂場鏈接
但是,這通常是一種反模式。一個更好的方法,特別是因為它會在編譯時與 TypeScript 一起作業,是提供Dog一些Animal沒有的功能并測驗該功能:
class Animal {
}
class Dog extends Animal {
bark() {
console.log("Woof!");
}
}
//This obj can have either class
const mixedObj/*: Animal | Dog*/ = new Dog();
console.log("bark" in mixedObj); // returns: `true` (would be `false` for an `Animal`)
if ("bark" in mixedObj) {
mixedObj.bark(); // No error, because TypeScript knows that it's a `Dog`
}
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467357.html
標籤:javascript 节点.js 打字稿 表示 下一个.js
上一篇:試圖對懸停圖片進行故障排除
