My current code is not working as expected:
export function extendObject<
T extends Object,
X extends Object,
>(x: T, a: X): T & X {
const p = { __proto__: x }
Object.assign(p, a)
return p
}
However, I am encountering an error when I reach the return p
part:
Type '{ __proto__: T; }' is not assignable to type 'T & X'.
Type '{ __proto__: T; }' is not assignable to type 'T'.
'{ __proto__: T; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Object'.ts(2322)
Originally, the code was in JavaScript and looked like this:
export function extendObject(x, a) {
const p = { __proto__: x }
Object.assign(p, a)
return p
}
Here is how I would use it in JavaScript:
const a = { foo: 'bar' }
const b = extendObject(a, { one: 2 })
assert(b.foo === 'bar')
assert(b.one === 2)
I am struggling to properly type this in TypeScript to make it compile. I would prefer to use __proto__
for performance reasons, but if that's not feasible, how else can I achieve a similar outcome?
I also attempted a different approach, but it didn't work:
export function extendObject<
T extends Object,
X extends Object,
>(x: T, a: X): T & X {
const p: T & X = {}
Object.keys(x).forEach(key => (p[key] = x[key]))
Object.keys(a).forEach(key => (p[key] = a[key]))
// Object.assign(p, a)
return p
}