TS2536

error TS2536: Type string cannot be used to index type Config

Broken Code ❌

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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;
},
});
}
}