Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript constructor with spread operator

Tags:

typescript

Need to assign porperties to the only defined from the interface if used with spread operator.

I am expecting a solution for using typescript constructor with spread operator.

For eg.

export interface IBrand {
    id: string;
    name: string;
}

export class Brand implements IBrand {
    id: string;
    name: string;       

    constructor(data: IBrand) {
        this.id = data.id;
        this.name = data.name;
    }
}

this is one option so the moment when I call this class like this, no way how many members are there but I would be having only id, name to final object.

new Brand({...data })

Case: But when I have 25+ keys to the data

export interface IBrand {
    id: string;
    name: string;
}

export class Brand implements IBrand {
    id: string;
    name: string;       

    constructor(data: Partial<IBrand>) {
        Object.assign(this, data);
    }
}

I am expecting not to write all properties again constructor. No matter it has 25 it would be just assigning that existing properties would be assigned. If data has section, genre or any other property it would be ignored.

My 2nd snippet doesn't work.

like image 863
Sankalp Avatar asked Jan 01 '23 00:01

Sankalp


1 Answers

This doesn't use the spread operator, but you could use the method from this answer

constructor(data: IBrand) {
    for (let key in data) {
        this[key] = data[key];
    }
}

then instantiate...

new Brand(data);
like image 189
Homer Avatar answered Mar 16 '23 14:03

Homer