I can't understand why TypeScript throw out the error
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
How to fix error?
If you analyze the error message given, it says the following thing:
Property 'idBlock' does not exist on type 'ChatActionTypes'.
Property 'idBlock' does not exist on type 'SendMessageAction'.
typescript cannot deduce from your usage that the action: ChatActionTypes
is a DeleteMessageAction
, as you have specified it as a ChatActionTypes
. So Typescript warns you that it can't find it on 2 out of 3 possible matches for the ChatActionTypes
.
If you would first validate the type
on the action
argument, typescript would be able to deduce that action is at that time a DeleteMessageAction
, for example by doing:
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.