以下是抽象的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:");
};
在控制台日志记录时抛出TypeScript错误test.okay
,因为它显然不存在。
Property `okay` does not exist on type `UndetereminedEmotion`.
即使传递给该方法的测试类型为,也很可能存在EmotionsOkay
。
为什么会这样?
此时,TS不知道它是什么类型,可能是什么类型EmotionsOkay
,一切都会好起来,或者可能是,EmotionsNotOkay
并且该属性okay
将不存在。这就是为什么您会收到此错误。您需要验证它是哪种类型。
您可以使用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:");
};
如果您首先没有财产okay
,您就不会幸福。
如果您想知道为什么不能instanceof
在这种情况下使用,请查看此问题
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句