I am trying to create a function that takes in a key and a value and updates that corresponding key-value pair on a typed object. Here is a basic example of what I am after.
Link to code sandbox with below code
type x = {
prop : number,
other : string
}
let dataToUpdate : x = {
prop: 1,
other: "string"
}
function updateKey(key : string, value : number | string) {
dataToUpdate[key] = value;
}
I am getting this error with the above implementation.
Element implicitly has an
'any'
type because expression of type'string'
can't be used to index type'x'
. No index signature with a parameter of type'string'
was found on type'x'
.(7053)
Update I was introduced to the idea of an XY Problem. Below is the actual implementation I am after. I am trying to create a context within React that returns a function that allows you to only update a specific property within the object that is stored in the context
export function StoreProvider(props: any) {
const [storeData, setStoreData] = useState<StoreData>(initProviderData);
function setStoreKeyValue(keyToUpdate: keyof StoreData[], valueToSet: boolean | string | number | null){
let newStoreData = {...storeData);
const isStoreData = Object.keys(initProviderData).filter((key) => { key == keyToUpdate }).length > 1;
if (isStoreData && newStoreData) {
newStoreData[keyToUpdate] = valueToSet;
setStoreData(newStoreData)
}
}
return (
<StoreContext.Provider value={{ "storeData": storeData, "setStoreData": setStoreData }}>
{props.children}
</StoreContext.Provider>
)
}