TS2536
Type
stringcannot be used to index typeConfig
Broken Code ❌
export type StrategyConfig = {
[key: string]: string;
};
export class GenericClass<Config extends StrategyConfig> {
public proxyConfig(source: Config): Config {
return new Proxy<Config>(source, {
set: <ConfigKey extends keyof Config>(config: Config, property: string, value: Config[ConfigKey]) => {
config[property] = value;
return true;
},
});
}
}Fixed Code ✔️
Because the type of property is a string and Config expects a ConfigKey, we need to ensure that our property is of type ConfigKey.
We can simply annotate the ConfigKey type to property, but we also have to make sure that ConfigKey extends the string type as the set method of a Proxy only accepts string | symbol:
export type StrategyConfig = {
[key: string]: string;
};
export class GenericClass<Config extends StrategyConfig> {
public proxyConfig(source: Config): Config {
return new Proxy<Config>(source, {
set: <ConfigKey extends keyof Config & string>(config: Config, property: ConfigKey, value: Config[ConfigKey]) => {
config[property] = value;
return true;
},
});
}
}