打字稿 - 使用键变量更改字典的值 [英] Typescript - change value of a dictionary with a key variable
问题描述
我有一个对象:
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
}
错误说:
输入'字符串|number' 不能分配给类型 'never'.
Type 'string | number' is not assignable to type 'never'.
类型 'string' 不可分配给类型 'never'.ts(2322)
Type 'string' is not assignable to type 'never'.ts(2322)
TIA!!!
推荐答案
这里的问题是,如果您要为任意键分配一个值,那么该值必须具有可分配给您可能使用的每个键的类型将其分配给.这意味着值的类型必须是 string &number
以便可以分配给 string
和 number
属性类型.交集 string &number
是 never
.
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
.
解决方案是使用泛型类型,这样 upDatedValue
被约束为根据 key
的类型具有正确的类型:
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.
这篇关于打字稿 - 使用键变量更改字典的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!