[英]TypeScript how to set key value on a object
I got a problem about set key/value on a plain object.我遇到了关于在普通 object 上设置键/值的问题。
type getAObjectFn = <K extends string, V>(k: K, v: V) => Record<K, V>
const getAObject: getAObjectFn = (k, v) => {
return {
[k]: v
}
}
console.log(getAObject("foo", "bar"))
code is really simple while I got error:当我收到错误时,代码非常简单:
Type '{ [x: string]: V; }' is not assignable to type 'Record<K, V>'.
why I got this error?为什么我得到这个错误? I mean k has type K which extends string, so I think they are same.how to get correct result?
我的意思是 k 具有扩展字符串的 K 类型,所以我认为它们是相同的。如何获得正确的结果?
BTW, the type of getAObject("foo", "bar")
shows Record<"foo",string>
,why not Record<"foo","bar">
or Record<string,string>
?顺便说一句,
getAObject("foo", "bar")
的类型显示Record<"foo",string>
,为什么不显示Record<"foo","bar">
或Record<string,string>
?
If you don't need to use a more precise type than string I would suggest setting the key to string
.如果您不需要使用比 string 更精确的类型,我建议将键设置为
string
。
type getAObjectFn = <V>(k: string, v: V) => Record<string, V>
const getAObject: getAObjectFn = (k, v) => {
return {
[k]: v
}
}
However if you want a more precise type you could do a typecast, it should be safe in this scenario.但是,如果您想要更精确的类型,您可以进行类型转换,在这种情况下应该是安全的。
type getAObjectFn = <K extends string, V>(k: K, v: V) => Record<K, V>
const getAObject: getAObjectFn = (k, v) => {
return {
[k]: v
} as Record<typeof k, typeof v>
}
My guess is that the reason you need to do this is that []
-operator doesn't preserve the type of k
(just my guess however).我的猜测是你需要这样做的原因是
[]
-operator 不保留k
的类型(不过只是我的猜测)。 By doing the type cast you restore the type of the key.通过执行类型转换,您可以恢复密钥的类型。
Further on I'm guessing that the reason that getAObject("foo", "bar")
returns a Record<"foo",string>
is that the type K extends string
makes the compilator look for a more specific type than string
and finds the type "foo"
, while for V
it is satisfied with string
.此外,我猜测
getAObject("foo", "bar")
返回Record<"foo",string>
的原因是类型K extends string
使编译器寻找比string
更具体的类型并找到类型"foo"
,而对于V
它满足于string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.