Conditional Generic Types in TypeScript use Discriminated Union

I have two interfaces in my code that I want to select one type between these two.

Here is the code for the interfaces:

interface createUserToSiteMutateUseStates {
  setStateId: (value: React.SetStateAction<string | null | undefined>) => void;
  StateId: string | null | undefined;
  setCityId: (value: React.SetStateAction<string | null | undefined>) => void;
}

interface updateStoreSpatialCommitmentsVariablesUseState {
  setStateSelected: (
    value: React.SetStateAction<SelectorOptions[] | undefined | null>
  ) => void;
}

I created a type to recognition of true interface:

type whichType<T> = T extends "createUserToSiteMutate"
  ? createUserToSiteMutateUseStates
  : T extends "updateStoreSpatialCommitmentsVariables"
  ? updateStoreSpatialCommitmentsVariablesUseState
  : null;

And finally I used the whichType:

export interface Props {
  type:
    | "createUserToSiteMutate"
    | "createUnitVariables"
    | "updateStoreSpatialCommitmentsVariables";
  useStateProps?: whichType<type>;
}

But when I use Props, I get this error:

const handleChange = (option: SelectorOptions) => {
      switch (type) {
        case "createUserToSiteMutate":
          useStateProps!.setCityId && useStateProps!.setCityId(null);
          useStateProps!.setUniversityId &&
            useStateProps!.setUniversityId(null);
          useStateProps!.setOrganizationId &&
            useStateProps!.setOrganizationId(null);
          useStateProps!.setUnitId && useStateProps!.setUnitId(null);
          useStateProps!.setStateId && useStateProps!.setStateId(option.value);
        default:
          break;
      }
    };

Property ‘setCityId’ does not exist on type ‘createUserToSiteMutateUseStates | updateStoreSpatialCommitmentsVariablesUseState’.

Property ‘setCityId’ does not exist on type ‘updateStoreSpatialCommitmentsVariablesUseState’.ts(2339)

How can I fix this error? Is a problem in whichType?

56 thoughts on “Conditional Generic Types in TypeScript use Discriminated Union”