简体   繁体   中英

Typescript interface type mapping to an object that consists of an original object and a new object built from original object's fields

I would like to map a type X to another type Y that consists of X and Z, where Z contains two values of X. Sounds convoluted, so you'll find the code below.

I have a following model for a data object from a database:

export interface Task {
 description: string;
 name: string;
 beginDate: string;
 endDate: string;
}

Having made a call to the DB, I would like to map these objects to the following type:

export interface TaskWithDate {
 task: Task;
 fullDate: FullDate;
}

where FullDate is an interface with the following definition:

export Interface FullDate {
 beginDate: string;
 endDate: string;
}

...and it should be filled with beginDate and endDate from a Task .

So, I make a call to the DB and want to do the mapping:

tasks: Task[];
this.tasks = this.getAllTasks(); // db call
this.ticketsWithDate = this.tasks.map(
      t => { return <TasktWithDate>{ task: t, fullDate: null }}
    );

Question: How can I grab the startDate and endDate of Task ( t ) to create a FullDate object within the map function?

Iterate over the task array as you have done and then map the corresponding fields you need from it to form the TaskWithDate array as illustrated below:

ticketsWithDate: TaskWithDate[];

this.ticketsWithDate = this.tasks.map(
  tsk => {
    return {
      task: tsk,                       // map entire task object
      fullDate: {                      // fetch begin and end dates from task to 
        beginDate: tsk.beginDate,      // form a new key i.e fullDate
        endDate: tsk.endDate
      }
    };
  }
);

It's simple , why don't you try just this,

this.ticketsWithDate = this.tasks.map(
    t => { 
        let fullDate: FullDate = {
            beginDate = t.beginDate,
            endDate = t.endDate
        }

        return <TasktWithDate>{ task: t, fullDate: fullDate }
    }
);

Or this,

this.ticketsWithDate = this.tasks.map(
t => { 
    return <TasktWithDate>{ task: t, fullDate: {
        beginDate = t.beginDate,
        endDate = t.endDate
    }
    }
}

);

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