从一个接口映射到另一个接口

Map from one interface to another

我来自 Java,我通常使用 DTO 映射到实体,反之亦然。但是我很难在 Typescript + Nodejs 中做到这一点。我有两个接口:

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

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

在接口一格式上收到 GET 调用,接口二负责获取此响应并在之后发出 POST 请求。

下面的实现得到 undefined:

let userTwo: ITwo;

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

在 Typescript/Nodejs 中以一种接口格式映射返回的响应然后将 DTO 中的另一种接口格式转换为域对象模式的正确方法是什么?

你可以这样做:

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))
}

可以在以下文章中找到有关如何在 TypeScript 中实现 DTO 的综合指南:

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

它包含更多详细信息,但也展示了实施您所要求内容的良好做法。