Typescript: Is there a simple way to convert an array of objects of one type to another

You haven’t showed enough of your code, so I’m not sure how you instantiate your classes, but in any case you can use the array map function:

class Item {
    name: string;
    desc: string;
    meta: string
}

class ViewItem {
    name: string;
    desc: string;
    hidden: boolean;

    constructor(item: Item) {
        this.name = item.name;
        this.desc = item.desc;
        this.hidden = false;
    }
}

let arr1: Item[];
let arr2 = arr1.map(item => new ViewItem(item));

(code in playground)


Edit

This can be shorter with Object.assign:

constructor(item: Item) {
    Object.assign(this, item);
}

Leave a Comment