Mike Cluck
Mike Cluck

Reputation: 32511

Typesafe assign to object at key from string

I'm trying to figure out how to create a typescript setter function which takes in an object, a key of that object, and a value to assign at that key.

Here's what I have so far:

const setter = <T, K extends keyof T>(obj: T, key: K, value) => {
  obj[key] = value
}

const obj = {
  a: 1,
  b: 'two',
}

setter(obj, 'a', 2) // works fine
setter(obj, 'c', 3) // correctly fails since `obj` does not have a `c` prop
setter(obj, 'b', 4) // works but should not be possible

How can I type this function such that value matches the type at T[K]?

Upvotes: 1

Views: 93

Answers (1)

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

Sure, just type value as T[K]

<T, K extends keyof T>(obj: T, key: K, value: T[K])

Upvotes: 2

Related Questions