1

In my code I often have to copy data from json to instantiate class in constructor.

function append(dst, src) {
    for (let key in src) {
        if (src.hasOwnProperty(key) {
            dst[key] = src[key];
        }
    }
};


export class DataClass {
    id: number;
    title: string;
    content: string;
    img: null | string;
    author: string; 
    // no methods, just raw data from API
}


export class AdoptedClass1 extends DataClass {
    // has same fields as DataClass
    showcase: string;

    constructor (data: DataClass) {
        append(data, this);

        // do some stuff
    }
}


// similar code for AdoptedClass2 

I'm wondering if I can replace append function call in constructor with object spread operator

2 Answers 2

4
+50

For your need I'll prefer to use Object.assign(this, data) over your custom made append function. Nevertheless have a look at the documentation to understand the limitation of it.

Back to your main question: it is not possible to use the spread operator to do what you want. Many people are interested in that feature but it has been put on hold as you can see here.

To get closer of what you ask we can refactor your code a little:

export class DataClass {
    id: number
    title: string
    content: string
    img: null | string
    author: string
    constructor(data: DataClass) {
        Object.assign(this, data)
    }
}

export class AdoptedClass1 extends DataClass {
    showcase: string

    constructor (data: DataClass) {
        super(data)

        // do some stuff
    }
}

By simply adding the constructor to the data class you will be allowed to use super(data) in children and IMHO the code will be a lot cleaner.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use object spread operator by replacing this line:

append(data,this)

with this line

data = {...data, ...this};

1 Comment

this would set the incoming argument, not the instance of the class itself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.