[Solved] Switch with specific type in TypeScript not working


Just replace your object with an enum, that’s what they’re for:

export enum APP_STATUS {
  CONFIRMED,
  INCONSISTENCIES,
  SUCCESS,
  ERROR,
  LOADING,
  OK,
}

export interface Inconsistency {};

export interface InconsistenciesLoading {
  type: APP_STATUS.LOADING;
}

export interface InconsistenciesError {
  type: APP_STATUS.ERROR;
}

export interface InconsistenciesSuccess {
  type: APP_STATUS.SUCCESS;
}

export interface InconsistenciesData {
  type: APP_STATUS.INCONSISTENCIES;
  data: Inconsistency[];
}

type ViewState = InconsistenciesData | InconsistenciesSuccess | InconsistenciesLoading | InconsistenciesError;

export const component = ({ state }: { state: ViewState }) => {
    switch (state.type) {
        case APP_STATUS.INCONSISTENCIES:
            console.log(state.data); // Look ma, no error!
    }
};

Playground

Your version fails because unlike an enum your APP_STATE constant is actually just a regular mutable object: there’s no guarantee that your compile-time type will still hold when the switch statement actually takes effect at runtime.

0

solved Switch with specific type in TypeScript not working