Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS2536:Type 'keyof T2' cannot be used to index type 'T1'

Tags:

typescript

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?

like image 568
user656449 Avatar asked Jan 09 '17 15:01

user656449


1 Answers

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?

like image 164
Motti Avatar answered Sep 19 '22 13:09

Motti