简体   繁体   中英

Extending Type with new property isn't working

I'm trying to add one property to an existing Type. Here's my type:

const dialogData: DialogData = {
    a: string,
    b: string,
    c: string
}

I extend it like this:

export type ExtendedDialogData = DialogData & {
    d: number
} 

But when I try to create the object it's failing. My syntax must be completely wrong:

const myData: DialogData[{a:0, b:1, c:2}, {a:3, b:4, c:5}]
const myExtendedData: ExtendedDialogData[] = [...myData, d: 100 ];

The error is on d and says cannot find name 'd' . Also, in actuality, I just want d to be a copy of whatever c is. Can someone please help me understand my syntax error?

UPDATE: As requested, here's the real code. In a Material dialog in Angular I have these two types:

export type EditableDataModel = MyDataModel & {
    sharesToMove: MyDataModel[];
}

export interface MyOrdersDialogData {
    title: string,
    orders: EditableDataModel[]
}

In the component that launches the model, I have this:

public launchModal() {
    const orders: EditableDataModel[] = [...this.selectedOrders.map(el => {...el, sharesToMove: el.shares})[;
}

I can console.log inside the map and see the orders output like this:

{
    title: 'my title', 
    orders: 1556
}

Here, you are trying to add d directly to the array instead of adding to each object inside the array. You can try like the following

const myData: DialogData[{a:0, b:1, c:2}, {a:3, b:4, c:5}]
const myExtendedData: ExtendedDialogData[] = [...myData.map(el => ({...el, d: 100})) ];

This will add the d property to each item in the array

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