TypeScript: Incorrect Type Inference for Property with Conditional Type in Abstract Class

38 Views Asked by At

I have a generic abstract class which has a property with a conditional type.

interface Catalogue<T extends Item> {
    findById(id: T["id"]): T | undefined;
    // ...
}

type CatalogueOrConfigManager<T extends Item | Config> = T extends Item ? Catalogue<T> : T extends Config ? ConfigManager<T> : never;

abstract class BaseStore<T extends Item | Config> {
    protected hotStore: CatalogueOrConfigManager<T>;
    // ...
}

when I extend abstract class and try to use the property with conditional type typescript is not inferring its type correctly.

class HotCatalogue<T extends Item> extends BaseStore<T> {
    findById(id): Promise<T | undefined> {
        const doc = this.hotStore.findById(id);
        return doc; // Type 'Item | undefined' is not assignable to type 'T | undefined'.
    }
}

In the HotCatalogue class that extends BaseStore, TypeScript incorrectly infers return the type of this.hotStore.findById as Item | undefined instead of T | undefined. As a result, I get a type error when returning the doc variable.

I tried using the conditional type directly on the property instead of creating a type for it.

abstract class BaseStore<T extends Item | Config> {
    protected hotStore: T extends Item ? Catalogue<T> : T extends Config ? ConfigManager<T> : never;
    // ...
}

it didn't work.

I am not sure but maybe it's happening because of limitation described in this answer. If so, I would appreciate if anyone can explain how it is relating to my issue. What can I do to fix it, or avoid this from happening?

0

There are 0 best solutions below