我正在學習 Typescript(和 React),并且正在嘗試檢查物件是否為 null 以跳過進一步的處理。我在下面有一個最小的例子。
如果 inputCat 為 null,我想立即回傳以跳過進一步處理,我該如何在 TypeScript 中執行此操作?
declare class Cat {
color: string;
// lots of more properties here
}
const processCat = (inputCat: Cat): Cat => {
if(!inputCat) {
return {}; // throws error: "Property 'color' is missing in type '{}' but required in type 'Cat'."
}
// lots of processing here
return {
... inputCat,
// lots of new variables here
}
}
當我嘗試回傳一個空物件時,TypeScript 抱怨說:
“{}”型別中缺少屬性“顏色”,但在“貓”型別中是必需的。
如何在 Typescript 中回傳空物件或 null?還是我以錯誤的方式解決這個問題?
uj5u.com熱心網友回復:
添加null到回傳型別(使用聯合型別Cat | null)
const processCat = (inputCat: Cat): Cat | null => {
if(!inputCat) {
return null;
}
// lots of processing here
return {
... inputCat,
// lots of new variables here
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463612.html
