首页 > 解决方案 > 类型上不存在属性但属性存在

问题描述

我不明白为什么 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

如何修复错误?

标签: javascripttypescript

解决方案


如果您分析给出的错误消息,它会说以下内容:

类型“ChatActionTypes”上不存在属性“idBlock”。

“SendMessageAction”类型上不存在属性“idBlock”。

无法从您的用法中推断出 theaction: ChatActionTypes是 a DeleteMessageAction,因为您已将其指定为 a ChatActionTypes。因此,Typescript 会警告您,它在ChatActionTypes.

如果您首先验证typeonaction参数,则将能够推断出当时的动作是 a 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
   }
}

推荐阅读