2

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!

spaceemotion
  • 1,404
  • 4
  • 24
  • 32
  • The compiler cannot analyze higher order generic conditional types like this; see https://github.com/microsoft/TypeScript/issues/30728. Additionally it actually isn't technically safe to assign `model[key] = value` since perhaps `T` is `{a: "someSpecificString"}`. My suggestion here would be to flip your constraints so that only `K` is generic, like [this](https://tsplay.dev/wjZX7w); a value of type `Record` allows you to write a `string` to the `K` index (this turns out also not to be safe in the same way, but the compiler allows it ) – jcalz Apr 13 '22 at 15:40

0 Answers0