英文:
Can I give a useful generic type to a function that copies an object with a key added or replaced with a new value?
问题
我已经编写了以下函数:
function extend(obj, key, value) {
return { ...obj, [key]: value }
}
理想情况下,我希望能够通用地使用这个函数,其中obj
是一个在调用点已知类型的Object
,key
是在调用点保持不变的字符串,value
是在调用点已知类型的值。obj
可能已经包含key
,而与该键关联的旧值可能与新的value
的类型相同也可能不同。
我已经查看了Utility Types 参考,但我无法找到任何可以用来为extend
编写有用类型的内容。这是否可能?
英文:
I have written the following function:
function extend(obj, key, value) {
return { ...obj, [key]: value }
}
Ideally, I'd like be able to use this function generically, with obj
being an Object
whose type will be known at the callsite, key
being a string which is constant at the callsite, and value
a value whose type is known at the callsite. obj
might or might not already contain the key
, and the old value associated with that key may or may not be of the same type as the new value
.
I've looked through the Utility Types reference, but I can't see anything that would allow me to write a useful type for extend
. Is this possible?
答案1
得分: 1
function extend<T extends object, Key extends PropertyKey, Value>(obj: T, key: Key, value: Value): T & Record<Key, Value> {
return { ...obj, [key]: value } as T & Record<Key, Value>;
}
英文:
You need generics (read the whole page to understand what is going on here):
function extend<T extends object, Key extends PropertyKey, Value>(obj: T, key: Key, value: Value): T & Record<Key, Value> {
return { ...obj, [key]: value } as T & Record<Key, Value>;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论