Skip to content

Issue in inferring types in Switch Case for object methods having union mapped types. #51563

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
kansalanmol0609 opened this issue Nov 16, 2022 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@kansalanmol0609
Copy link

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.

@fatcerberus
Copy link

Duplicate of #30581, but see #30581 (comment)

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Nov 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants