我有一個函式被呼叫:
const accountDetails: IAccount | ISmallError = getAccount()
它可能會回傳 IAccount 或 ISmallError。
在下一行我想這樣做:
if (accountDetails.error) return response.json({ error: error.error });
但在.error
它下面說
Property 'error' does not exist on type 'IAccount | ISmallError'.
Property 'error' does not exist on type 'IAccount'.ts(2339)
我該怎么辦?
一種有效的解決方案是:
const err = accountDetails as ISmallError;
if (err.error) return response.json({ accountDetails: "No account found" });
但這是最好的方法嗎?
uj5u.com熱心網友回復:
假設該屬性是一個判別屬性,那么簡單'error' in accountDetails
就足夠了:
type IAccount = { payload: 2 }
type ISmallError = { error: Error }
declare const getAccount: () => IAccount | ISmallError;
const accountDetails: IAccount | ISmallError = getAccount()
if ('error' in accountDetails) {
accountDetails.error // No longer an error
}
使用屬性存在檢查更好(在我看來),因為它使用型別系統而不是覆寫它(就像強制轉換那樣),確保我們將來在更多情況下會出錯。
更好的是引入適當的判別屬性 IAccount
,ISmallError
以便您可以打開標簽。這有助于避免將來IAccount
發展自己的 error
領域的情況(更少的沖突位置使得代碼庫更易于維護):
type IAccount = { type: 'accountDetails', payload: 2 }
type ISmallError = { type: 'prodError', error: Error }
// ... snip ...
if (accountDetails.type === 'prodError') {
// Full narrowing here and no potential overlapping fields later
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517348.html
標籤:打字稿