The swagger-api/swagger-codegen generates following code:
private extendObj<T1,T2>(objA: T1, objB: T2) {
for(let key in objB){
if(objB.hasOwnProperty(key)){
objA[key] = objB[key];
}
}
return <T1&T2>objA;
}
which yields the error when compiling:
TS2536:Type 'keyof T2' cannot be used to index type 'T1'
Could somebody please explain why one object's key can't be used to access another's object fiel? Is the key inferred to some special type?
And what would be the correct way to copy object's properties in typescript?
I think the correct function should look like this:
function extendObj<T1,T2>(objA: T1|T2, objB: T2): T1|T2 {
for(let key in objB){
if(objB.hasOwnProperty(key)){
objA[key] = objB[key];
}
}
return objA;
}
The returned type should be the union of T1
and T2
(|
) not the intersection (&
).
Perhaps you're not familiar with keyof
it's a new feature in TypeScript 2.1.
I suppose the reasoning of the compiler is that it knows that key
is a valid member of T2
but it doesn't know about T1
that's why I say that objA
is a union of T1
and T2
(it isn't really but I want to assign to the keyof T2
fields). The compiler isn't differentiating between reads and writes.
I'm not familiar with swagger-codegen, do you have any control on, or can you edit, the generated code?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With