'Typescript switch generic type guard
I have a method that gets 2 params:
- Enum type
- 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;
}
};
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;
};
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 |
|---|


