简体   繁体   中英

Typescript copy properties of an object using for..in

I'm trying to copy the properties of an object using for..in but I got the error:

Type 'Greeter[Extract]' is not assignable to type 'this[Extract]'.

Any ideas how to solve this?

class Greeter {
a: string;
b: string;
c: string;
// etc

constructor(cloned: Greeter) {

    for (const i in this) {
        if (cloned.hasOwnProperty(i)) {
            this[i] = cloned[i];
        }
    }
}

Here is the sample in the typescript playground.

Thanks!

The problem is that the type of this is not Greeter it's the polymorphic this type . An unfortunate consequence is that the i in your for loop i typed as keyof this while Greeting can be indexed using a keyof Greeting . These may seem like the same thing, but if you consider that Greeting can be derived, keyof this could potentially contain a lot more members. A similar discussion applies to the value of the indexing operation.

The compiler is not wrong, this may have more keys than Greeter so this is not 100% safe.

The simplest solution is to use a type assertion to change the type of this :

class Greeter {
    a: string;
    b: string;
    c: string;
    // etc

    constructor(cloned: Greeter) {
        for (const i in this as Greeter) {
            if (cloned.hasOwnProperty(i)) {
                this[i] = cloned[i]
            }
        }

    }
}

Or you can iterate over the cloned object:

class Greeter {
    a: string;
    b: string;
    c: string;
    // etc

    constructor(cloned: Greeter) {
        for (const i in cloned) {
            if (cloned.hasOwnProperty(i)) {
                this[i] = cloned[i]
            }
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM