Home > Mobile >  Map from one interface to another
Map from one interface to another

Time:09-17

I'm coming from Java and I usually use DTO to map to Entity and vice-versa. But I'm having a hard time to do this in Typescript Nodejs. What I have are two interfaces:

export interface IOne {
    clientId: number;
    clientName: string;
    ...
}

export interface ITwo {
    userId: number;
    userName: string;
    ...
}

A GET call is received on Interface One format and Interface Two is responsible to grab this response and make a POST request after.

The bellow implementation gets undefined:

let userTwo: ITwo;

userTwo.map(data => {
    return <ITwo> {
        userId: data.clientId,
        userName: data.clientName,
        ...
    };
});

What is the right way in Typescript/Nodejs to Map the returned response in one interface format then convert to another Interface format in DTO to Domain Object pattern?

CodePudding user response:

You could do something like this:

export interface IOne {
    clientId: number;
    clientName: string;
    ...
}

export interface ITwo {
    userId: number;
    userName: string;
    ...
}

const toDTO = (input: IOne): ITwo => {
  return {
    userId: input.clientId,
    userName: input.clientName
  }
}

const handleReq = (req) => {
  // we assume you have to tell Typescript what userOne is
  const userOne = req.userOne as IOne[]
  // userTwo will be typed as ITwo[] or Array<ITwo> through inference
  const userTwo = userOne.map(u => toDTO(u))
}

CodePudding user response:

A comprehensive guide to how to implement DTOs in TypeScript can be found in the following article:

https://khalilstemmler.com/articles/typescript-domain-driven-design/repository-dto-mapper/

It contains more details, but it also shows the good practices of implementing what you asked.

  • Related