Dan
Dan

Reputation: 57881

Using Typescript object spread operator with this keyword

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

Upvotes: 1

Views: 1519

Answers (2)

TamerB
TamerB

Reputation: 1441

You can use object spread operator by replacing this line:

append(data,this)

with this line

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

Upvotes: 0

jrmgx
jrmgx

Reputation: 729

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.

Upvotes: 4

Related Questions