How to define a generic Type Guard in Typescript?

Discussão em 'Angular' iniciado por distante, Fevereiro 14, 2025.

  1. distante

    distante Guest

    I want to define an interface for my classes that contains a isValidConfig function to be used as type guard. But I am not sure how to declare it.

    I have done this:

    type AnyConfig = ConfigA | ConfigB | ConfigC;

    public abstract isValidConfig<T extends AnyConfig>(config: AnyConfig): config is T;



    and

    public abstract isValidConfig<T = AnyConfig>(config: T): config is T;


    But I always get errors in the implementation like:

    public isValidConfig<T extends ConfigA >(config: T): config is T {
    return config.type === TrainingTypes.A;
    } /// Types of parameters 'config' and 'config' are incompatible.
    Type 'T' is not assignable to type 'ConfigA '.


    Is it possible to do this? I haven't found the way.

    Continue reading...

Compartilhe esta Página