簡體   English   中英

類型上不存在屬性但屬性存在

[英]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: ChatActionTypesDeleteMessageAction ,因為您已將其指定為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM