How does variance work when implementing interfaces/type aliases in TypeScript?

26 views Asked by At

I have the following types :

interface Config {
    configurable: boolean;
    cancelable: boolean;
    isUnique: boolean;
}

// Config Subtype
interface EnvironmentConfig extends Config {
    runtime: 'DEV' | 'PROD';
}

// Config Subtype
interface AnalogConfig extends Config {
    pulse: boolean;
}

enum ConfigKeys {
    initConfig = 0,
    customConfig = 1
}

type Run = {
    [Key in ConfigKeys]?: (config: Config) => Config
}

If I want to implement Run in a class, it throws an error, since when implementing it it only allows me to define the type Config, it could not specify a subtype of Config:

class Runner implements Run {
    [1](config: SpecialConfig) { // Error
        return config
    }

    [1](config: Config) { // Ok!
        return config
    }
}

How can I get it to allow me to declare a subtype of Config when implementing the Run type alias?

Is there any way? What other alternative can I apply?

0

There are 0 answers