I am trying to assign a value to the property of a generically typed object passed into a function. The object structure is unknown in advance and the property name is dynamically provided to the function as a string argument. Typescript throws the error "Type 'string' cannot be used to index type 'T'".
I have the following typescript code:
interface Value {
[key: string]: any
}
interface SomeInterface<T> {
key: string,
value: T
}
function someFunction<T extends Value>({ key, value }: SomeInterface<T>) {
value[key] = somevalue;
}
The line where I assign somevalue to value throws the error "Type 'string' cannot be used to index type 'T'", even though I specifically created the index signature in the interface Value.
Why is this?
If you make the generic type key of the object you want to assign value to then you easily have types for the key and corresponding value.