Reputation: 439
I have an object:
const sampleExpenseData = {
Time: "11-12-19",
Meals: 5130,
Pantry: 10,
Living: 10,
Others: 0,
Total: 74
}
I would like to define a function such that it will update the value of a specific key, what I have so far is:
const updateValueInDict = (
obj: typeof sampleExpenseData,
key: keyof typeof sampleExpenseData,
upDatedValue: string | number
): void => {
obj[key] = upDatedValue // this line throws error
}
The error says:
Type 'string | number' is not assignable to type 'never'.
Type 'string' is not assignable to type 'never'.ts(2322)
TIA!!!
Upvotes: 0
Views: 5166
Reputation: 51034
The problem here is that if you're assigning a value to an arbitrary key, then that value must have a type which is assignable to every key you might be assigning it to. That means the value's type has to be string & number
in order to be assignable to both string
and number
property types. The intersection string & number
is never
.
The solution is to use a generic type, so that upDatedValue
is constrained to have the right type depending on the type of key
:
const updateValueInDict = <K extends keyof typeof sampleExpenseData>(
obj: typeof sampleExpenseData,
key: K,
upDatedValue: (typeof sampleExpenseData)[K]
): void => {
obj[key] = upDatedValue
}
This also means that the arguments can be type-checked more strictly when the function is called.
Upvotes: 2