我不明白为什么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
中如何解决错误?
答案 0 :(得分:1)
如果您分析给出的错误消息,则说明以下内容:
类型'ChatActionTypes'不存在属性'idBlock'。
类型'SendMessageAction'上不存在属性'idBlock'。
typescript无法从您的使用中推断出action: ChatActionTypes
是DeleteMessageAction
,因为您已将其指定为ChatActionTypes
。因此,打字稿警告您,在ChatActionTypes
的3个可能匹配项中,找不到2个。
如果您首先验证type
参数上的action
,那么typescript可以推断出当时的动作是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
}
}