TypeScript: Conditional Type Annotations

Hello all,

I have a reducer as such:

function reducer(
  state: StateType = initialState,
  { type, payload }: { type: string; payload: ReducerPayloadType }
): StateType {
  switch (type) {
    case TYPES.setLocation:
      return { ...state, location: payload };
    case TYPES.setIsDark:
      return { ...state, isDark: payload };
    case TYPES.setName:
      return { ...state, name: payload };
    case TYPES.setUsageData:
      return { ...state, usageData: payload };
    case TYPES.setDailyBudget:
      return { ...state, dailyBudget: payload };
    case TYPES.setProductDetails:
      return { ...state, productDetails: payload };
    case TYPES.setMeterPoints:
      return { ...state, meterPoints: payload };
    case TYPES.setAccount:
      return { ...state, account: payload };
      return state;

I have defined the ReducerPayloadType as:

export type ReducerPayloadType =
  | string
  | ProductDetailsType
  | UsageDataType
  | MeterPointsType;

// NOTE: the other types in there are just complex objects

I am getting this error:

Type ‘ReducerPayloadType’ is not assignable to type ‘string’.
Type ‘UsageDataType’ is not assignable to type ‘string’.ts(2322)
index.ts(95, 3): The expected type comes from property ‘location’ which is declared here on type ‘StateType’

I understand the issue. I just want to know the best way to conditionally annotate my payload based on the action.type.

My best thought is:

switch (type) {
    case TYPES.setLocation:
      return { ...state, location: payload as string };
    case TYPES.setIsDark:
//... etc

But this does not seem like the correct way.

REDUX: Energy-App/index.ts at master · ShaunSHamilton/Energy-App (github.com)

TYPES: Energy-App/index.ts at master · ShaunSHamilton/Energy-App (github.com)

All help is appreciated.