[英]Property does not exist on type But property exist
我不明白為什么 TypeScript 會拋出錯誤
interface SendMessageAction {
type: 1;
}
interface DeleteMessageAction {
type: 2;
idBlock:string;
}
type ChatActionTypes = SendMessageAction | DeleteMessageAction;
const CounterReducer = (action:ChatActionTypes) => {
action.idBlock
}
Property 'idBlock' does not exist on type 'ChatActionTypes'.
Property 'idBlock' does not exist on type 'SendMessageAction'.
接口DeleteMessageAction 中存在字段 idBlock
如何修復錯誤?
如果您分析給出的錯誤消息,它會說明以下內容:
類型“ChatActionTypes”上不存在屬性“idBlock”。
類型“SendMessageAction”上不存在屬性“idBlock”。
打字稿無法從您的使用中推斷出action: ChatActionTypes
是DeleteMessageAction
,因為您已將其指定為ChatActionTypes
。 因此,Typescript 會警告您,它無法在ChatActionTypes
的 3 個可能匹配項中的 2 個中找到它。
如果您首先驗證action
參數上的type
, 打字稿將能夠推斷出該操作當時是DeleteMessageAction
,例如通過執行以下操作:
const CounterReducer = (action:ChatActionTypes) => {
if (action.type === 2) { // 2 is mentioned on DeleteMessageAction for type
action.idBlock; // so you can now do something with idBlock here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.