Unable to assign value to generically typed object

51 Views Asked by At

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?

2

There are 2 best solutions below

0
Max On

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.

interface Value {
  [key: string]: any
}

function someFunction<T extends keyof Value>({ key, value }: {key:T, value:Value[T]}) {
  value[key] = value;
}
0
Joel On

The problem is that you can call someFunction with a more specific type of Value.

someFunction<{'someKey': any}>(...);

In this case string can no longer be used to index value. Only someKey would be a valid index. You can rewrite SomeInterface in such a way, that it always has a key that can be used to index the value:

interface SomeInterface<T> {
  key: keyof T,
  value: T
}

Full example