Cannot assign to type where key only references said type on given object

Viewed 14

I am currently trying to build a helper method, where I work with string values on an arbitrary object. However, TypeScript can't seem to infer that "key" is only a key that accesses string-only values on the given object.

Here is what I got as an example so far:

const obj = {
  foo: '2022-04-02T15:41',
  bar: 42,
  baz: '2022-04-02T15:41',
}

type StringValues<T> = {
  [key in keyof T]: T[key] extends string ? key : never
}[keyof T]

const setString = <T, K extends StringValues<T>>(model: T, key: K, value: string) => {
  // Errors with "Type 'string' is not assignable to type 'T[K]'.(2322)"
  model[key] = value;
}

setString(obj, 'baz', 'hi')

What am I missing? Thanks in advance!

0 Answers
Related