属性不存在,但类型存在

时间:2019-11-25 15:23:35

标签: javascript typescript

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

字段idBlock存在于接口 DeleteMessageAction

如何解决错误?

1 个答案:

答案 0 :(得分:1)

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

  

类型'ChatActionTypes'不存在属性'idBlock'。

     

类型'SendMessageAction'上不存在属性'idBlock'。

无法从您的使用中推断出action: ChatActionTypesDeleteMessageAction,因为您已将其指定为ChatActionTypes。因此,打字稿警告您,在ChatActionTypes的3个可能匹配项中,找不到2个。

如果您首先验证type参数上的action,那么可以推断出当时的动作是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
   }
}