Can I give a useful generic type to a function that copies an object with a key added or replaced with a new value?

huangapple go评论158阅读模式
英文:

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是一个在调用点已知类型的Objectkey是在调用点保持不变的字符串,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&lt;T extends object, Key extends PropertyKey, Value&gt;(obj: T, key: Key, value: Value): T &amp; Record&lt;Key, Value&gt; {
    return { ...obj, [key]: value } as T &amp; Record&lt;Key, Value&gt;;
}

Playground

huangapple
  • 本文由 发表于 2023年3月4日 07:19:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定