I am defining an interface where one of the type of the property depends on a generic param P bound to an enum. I am using the following approach:
export enum Scopes {
Fruit = 'fruit',
Vegetables = 'vegetables',
}
export enum FruitItemTypes {
Strawberry = 'strawberry',
Rasberry = 'rasberry'
}
export enum VegetableItemTypes {
Potatoes = 'potatoes',
Carrots = 'currency',
}
export type ItemTypes = FruitItemTypes | VegetableItemTypes
interface ItemTypeForScope {
[Scopes.Fruit]: FruitItemTypes;
[Scopes.Vegetables]: VegetableItemTypes;
}
export interface Item {
id: string;
type: ItemTypes;
}
export interface ScopedItem<T extends Scopes> extends Item {
type: ItemTypeForScope[T];
}
export interface ScopedData<T extends Scopes> {
items: ScopedItem<T>[];
}
export type Data = { [scope in Scopes]: ScopedData<scope> };
I also want to use ScopedItem<T>
as the return type of the following function:
const getItemType = <T extends Scopes>(data: Data, scope: T): ScopedItem<T>[] => {
return data[scope].items
}
However I am getting the following error, but according to me the generic param T will eventually be one of the enum case.
Type 'ScopedItem<Scopes.Fruit>[] | ScopedItem<Scopes.Vegetables>[]' is not assignable to type 'ScopedItem<T>[]'.
Type 'ScopedItem<Scopes.Fruit>[]' is not assignable to type 'ScopedItem<T>[]'.
Type 'ScopedItem<Scopes.Fruit>' is not assignable to type 'ScopedItem<T>'.
Type 'Scopes.Fruit' is not assignable to type 'T'.
'Scopes.Fruit' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Scopes'.