Closed
Description
Bug Report
🔎 Search Terms
Issue in inferring types in Switch Case for object methods having union mapped types.
🕗 Version & Regression Information
Version - All versions upto v5.0.0-dev.20221116
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about mapped types, union types and switch cases.
⏯ Playground Link
Playground link with relevant code
💻 Code
enum Actions{
ACTIONA,
ACTIONB
};
type ActionA = {
type : Actions.ACTIONA,
payload: {
body: string;
message: object;
}
}
type ActionB = {
type : Actions.ACTIONB,
payload: {
message: object;
}
}
type ActionType = ActionA | ActionB;
const actionHandlers: {
[key in Actions.ACTIONA | Actions.ACTIONB]: (payload: Extract<ActionType, { type: key }>['payload']) => void
} = {
[Actions.ACTIONA]: ({body, message}) => console.log(body, message),
[Actions.ACTIONB]: ({message}) => console.log( message),
}
const performAction = (action: ActionType): void => {
switch(action.type){
case Actions.ACTIONA:
case Actions.ACTIONB:
return actionHandlers[action.type](action.payload); //Error here
}
}
🙁 Actual behavior
Getting this error -
Argument of type '{ body: string; message: object; } | { message: object; }' is not assignable to parameter of type '{ body: string; message: object; }'.
Property 'body' is missing in type '{ message: object; }' but required in type '{ body: string; message: object; }'.
🙂 Expected behavior
TypeScript compiler should have been able to infer that action.type
and action.payload
are connected. It looks like it is treating them as independent variables.