2
    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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.