Let me explain what I am trying to achieve and what is the problem.
I have the following interface:
interface ExampleInterface {
a: string;
b: number;
}
I have the following variable which implements my ExampleInterface:
const exampleVariable: ExampleInterface = {
a: 'hello world',
b: 0,
}
I have the following function which has to modify my exampleVariable, this function takes two params, the first param has to be a key of exampleVariable, the second param has to be a new value which I want to assign to the given key(which is passed as a first param):
const setState = (key, value) => {
exampleVariable[key] = value;
}
What I want to achieve is the following:
I want to make sure that if I pass a key equal to a as a first param, then Typescript won't let me to pass anything except value of type string because inside ExampleInterface type of a is equal to string.
What I tried to do:
I tried to add the following types for my function params:
const setState = (key: keyof ExampleInterface, value: ExampleInterface[keyof ExampleInterface]) => {
exampleVariable[key] = value;
}
But I keep getting the following Typescript error:
Type 'ExampleInterface[keyof ExampleInterface]' is not assignable to type 'string & number'.
Type 'string' is not assignable to type 'string & number'.
Type 'string' is not assignable to type 'number'.ts(2322)
I assume that types for the function params are not set correctly. Any advice is appreciated. Thank you.