'Typescript switch generic type guard

I have a method that gets 2 params:

  1. Enum type
  2. Entity

The 'Entity' type is based on the Enum type by using generics. I have a switch case on the enum, so I expect the entityToCreate to be the relevant type, but it doesnt work:

export interface INotWorkingWorkingExample {
  <T extends ENTITY_TYPES>(params: {
    entityType: T;
    entityToCreate: GenericEntityByEntityType<T>;
  })
}
const testNotWorkingInterface: INotWorkingWorkingExample = (
  {
    entityToCreate,
    entityType,
  }) => {
  if (entityType === ENTITY_TYPES.BILL) {
    // a is of type GenericEntityByEntityType
    const a = entityToCreate;
  }
};

enter image description here

But when I use generic on the function itself, it does work:

export interface IWorkingExample<T extends ENTITY_TYPES> {
  (params: {
    entityType: T;
    entityToCreate: GenericEntityByEntityType<T>;
  })
}

const testWorkingInterface: IWorkingExample<ENTITY_TYPES.BILL> = (
  {
    entityToCreate,
    entityType,
  }) => {
  // a is of type GenericBill
  const a = entityToCreate;
};

enter image description here

I wonder if this is a bug, as I expect the switch case to be a guard for the dependent entity.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source