albertjan
albertjan

Reputation: 7817

return type of function inferred incorrectly if the return statement is outside a switch statement

given

const ACTION_1 = "ACTION_1";
type ACTION_1 = "ACTION_1";

const ACTION_2 = "ACTION_2";
type ACTION_2 = "ACTION_2";

type ActionTypes = 
  | ACTION_1
  | ACTION_2

export type Reducer<S = any> = (
  state: S | undefined,
  action: ActionTypes
) => S

when I have this Reducer:

const reducer: Reducer<boolean> = (
  state = false,
  action
) => {
  switch (action) {
    case ACTION_1:
       return true;
    case ACTION_2:
       return false;
    default:
  }
  return state;
}

in strict mode it complains that this function has a return type of IState | undefined but when I swap the return state; at the end for a default: return state in the switch statement it is fine. Or even just an empty default: and leaving the return statement at the bottom will, placate the compiler.

With the return type it even recognises in vscode that the return statement is unreachable. I understand it has to take it into account because run time it doesn't know if the switch statement was actually exhaustive.

But even if I have the default, it does know the return is definitely unreachable and still it complains about the fact this function could return IState | undefined.

And even that is wrong because there's a default value for the state parameter. So it is never undefined.

Is this a bug? Or a known limitation?

Playground Link

Upvotes: 3

Views: 130

Answers (1)

albertjan
albertjan

Reputation: 7817

This was fixed in typescript version 3.8.

Upvotes: 1

Related Questions