1

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?

Rob
  • 11
  • 2
  • What about like [this](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGpwDYFcUG8BQyyA2gNYQCeAXMgM5hSgDmAujXCBfgL776iRYiFAGUA9gFsIASXDR4SADwAVAHzICRctToNmAGkLIAbphw1lPPjCwgEYYGJB1JEAGK37jkAApcybX0TMxRuGnEpWUEFCEV0bAhVAEoNI1MEskoWZABeZAByWld0nHyAbisgA)? – kennarddh Jul 14 '23 at 11:56

2 Answers2

1

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

Joel
  • 51
  • 4
0

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;
}
Max
  • 859
  • 5
  • 10