简体   繁体   中英

This expression is not constructable

I am trying to make an abstract class that any class Foo or Bar can extends, then the method below will return a new instance of that extending class

export abstract class CopyWithable {

    copyWith<K extends keyof this>(obj: Pick<this, K>):this {
        return new this.constructor({...this, ...obj})
    }
}

If I got the idea properly I can propose the solution when we get the prototype of the current instance, create descriptors for all own properties and return a new object with known proto and extended props:

abstract class CopyWithable {
    copyWith<K extends keyof this>(obj: Pick<this, K>): this {
        const proto = Object.getPrototypeOf(this);
        const properties = Object
            .entries({...this, ...obj})
            .reduce((props, [key, value]) => ({ ...props, [key]: { value } }), {});

        return Object.create(proto, properties);
    }
}

It may look a little bit crappy but if you find a more elegant way to do the same, share your version please

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