以下抽象的 TS 场景:
interface EmotionsOkay {
emotion: string;
okay: "yap";
}
interface EmotionsNotOkay {
emotion: string;
}
type UndetereminedEmotion = EmotionsOkay | EmotionsNotOkay;
const areYouOkay = (test: UndetereminedEmotion) => {
console.log(test.okay ? "happy :D" : "sad D:");
};
在控制台记录 test.okay
时抛出 TypeScript 错误,因为它显然不存在。
Property `okay` does not exist on type `UndetereminedEmotion`.
即使它很可能存在,但如果传递给该方法的测试是 EmotionsOkay
类型。
为什么会发生这种情况?
最佳答案
此时,TS 不知道它是什么类型,它可能是 EmotionsOkay
并且一切都会好起来的,或者它可能是 EmotionsNotOkay
并且属性 好吧
不会存在。这就是您收到此错误的原因。您需要验证它是什么类型。
您可以使用 in
关键字来验证这一点,
interface EmotionsOkay {
emotion: string;
okay: "yap";
}
interface EmotionsNotOkay {
emotion: string;
}
type UndetereminedEmotion = EmotionsOkay | EmotionsNotOkay;
const areYouOkay = (test: UndetereminedEmotion) => {
console.log('okay' in test && test.okay ? "happy :D" : "sad D:");
};
如果您一开始就没有属性(property)好吧
,您就不会快乐。
如果您想知道为什么在这种情况下不能使用 instanceof
,请查看 this question
关于Typescript:组合类型上不存在属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60078892/