简体   繁体   English

类型上不存在属性但属性存在

[英]Property does not exist on type But property exist

I can't understand why TypeScript throw out the error我不明白为什么 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'.

Field idBlock exist in interface DeleteMessageAction接口DeleteMessageAction 中存在字段 idBlock

How to fix error?如何修复错误?

If you analyze the error message given, it says the following thing:如果您分析给出的错误消息,它会说明以下内容:

Property 'idBlock' does not exist on type 'ChatActionTypes'.类型“ChatActionTypes”上不存在属性“idBlock”。

Property 'idBlock' does not exist on type 'SendMessageAction'.类型“SendMessageAction”上不存在属性“idBlock”。

cannot deduce from your usage that the action: ChatActionTypes is a DeleteMessageAction , as you have specified it as a ChatActionTypes . 无法从您的使用中推断出action: ChatActionTypesDeleteMessageAction ,因为您已将其指定为ChatActionTypes So Typescript warns you that it can't find it on 2 out of 3 possible matches for the ChatActionTypes .因此,Typescript 会警告您,它无法在ChatActionTypes的 3 个可能匹配项中的 2 个中找到它。

If you would first validate the type on the action argument, would be able to deduce that action is at that time a DeleteMessageAction , for example by doing:如果您首先验证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