John Grant
John Grant

Reputation: 82

Reference the value of a key in a typescript object

    type obj = { a: 1, b: "one", c: true }
    function updateObj(key: keyof obj, value: obj[typeof key] ) {

    }

Currently the parameter; value in the updateObj function is a union of all the values of the type obj. However, i want it to reference only the value of the key that was passed to the function.

Upvotes: 2

Views: 2081

Answers (1)

CRice
CRice

Reputation: 32146

Make the function generic. Use a generic parameter to represent the key that you get, and use that to access the key's value type:

type obj = { a: 1, b: "one", c: true }

declare function updateObj<K extends keyof obj>(key: K, value: obj[K]);

updateObj("a", 1)      // No error
updateObj("a", 5)      // Error here
updateObj("a", false); // Error here

Playground Link

Upvotes: 1

Related Questions