Skip to content

Contextual typing fails to throw error with function return type on left side of equals sign #38879

@danbockapps

Description

@danbockapps

TypeScript Version: I got the same behavior on 3.7.4 and 4.0.0-dev.20200601

Search Terms:
left side
right side
contextual typing
type inference

Code

interface ReportState {
  reportDefinition: {
    [key: number]: ReportDetails;
  };
}

interface ReportDetails {
  requiredNumber: number;
  columnWidths?: number[];
}

export const Report: (state: ReportState, action: any) => ReportState = (
  state,
  action
) => { // See note below about this line
  switch (action.type) {
    case "TYPE0": {
      const { reportDef, sequenceId } = action.payload;
      return {
        ...state,
        reportDefinition: {
          ...state.reportDefinition,
          [sequenceId]: {
            ...reportDef,
            selectedElements: ["0x0"],
          },
        },
      };
    }

    case "TYPE1": {
      return {
        ...state,
        reportDefinition: {
          ...state.reportDefinition,
          [action.payload.sequenceId]: {
            // requiredNumber is missing here. This should be an error.
            columnWidths: action.payload.columnWidths,
          },
        },
      };
    }

    default:
      return state;
  }
};

Expected behavior:
There should be an error, because requiredNumber is missing from the second return statement.

Actual behavior:
Compilation succeeds without error.

Curiosity 1:
If you add the return type on the right side of the =, i.e. by changing
) => {
to
): ReportState => {
, it correctly finds the error. This should not be necessary, because the return type is already specified on the left side of the =.

Curiosity 2:
If you remove the first case block, it correctly finds the error (which is in the second case block).

Playground Link: Click here

Related Issues:
No

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions