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"]);
updateSupermarket. Why don't you just saymySupermarket.isOpen = true?