1

I'm looking for a way to write function parameters to update an object's value given the key to update and the new value to update.

type SuperMarket = {
    isOpen: boolean;
    offers: string[];
    name: string;
};

const mySuperMarket: SuperMarket = {
    isOpen: true,
    offers: ["banana", "apple", "kiwi"],
    name: "Kwik-E-Mart",
};

// How to make this typesafe?
const updateSupermarket = (key: keyof SuperMarket, value: any) => {
    mySuperMarket[key] = value;
};

// Should work correctly
updateSupermarket("isOpen", true);

// Should throw TypeScript error
updateSupermarket("isOpen", "Aldi");

// Should throw TypeScript error
updateSupermarket("isOpen", ["melon", "milk", "sugar"]);
2
  • I don't understand, what is the deal with wrapping it within updateSupermarket. Why don't you just say mySupermarket.isOpen = true? Commented Aug 26, 2020 at 13:55
  • It is just an example. In my real application, the object is a react state and more deeply nested. Also the function is reused in multiple places. Commented Aug 26, 2020 at 15:37

1 Answer 1

4

You need to use a type parameter to capture the key passed in and you can then use an type query to type value in relation to the passed in parameter:

const updateSupermarket = <K extends keyof SuperMarket>(key: K, value: SuperMarket[K]) => {
    mySuperMarket[key] = value;
};

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.