1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

How can I share DTOs with validation between NestJS and Angular without duplication or using...

Discussão em 'Angular' iniciado por Arnaud Denoyelle, Julho 22, 2025.

  1. I'm working with:

    • NestJS on the backend
    • Angular on the frontend

    Both use TypeScript, which makes it convenient to share Data Transfer Objects (DTOs) via a shared library.

    The challenge arises when I try to validate data.

    According to the NestJS documentation on validation, the recommended approach is to use class-validator and class-transformer.

    However, these libraries are not ESM-compatible, which leads to warnings during the Angular build process:

    ▲ [WARNING] Module 'validator/lib/isVariableWidth' used by 'node_modules/class-validator/esm2015/decorator/string/IsVariableWidth.js' is not ESM

    CommonJS or AMD dependencies can cause optimization bailouts.


    I explored Zod, which appears to be ESM-compatible. But I ran into issues with two specific TypeScript patterns:

    1. Enums using as const (enums without the enum keyword):

    export const UserTypeEnum = {
    USER: "USER",
    ADMIN: "ADMIN"
    } as const;

    export type UserType = (typeof UserTypeEnum)[keyof typeof UserTypeEnum];

    1. Branded types for stronger type safety:

    declare const __brand: unique symbol;
    type Brand<B> = { [__brand]: B };
    export type Branded<T, B> = T & Brand<B>;

    export type UserId = Branded<string, "UserId">;


    I’m looking for a solution that allows me to:

    • Define shared DTOs with validation logic.
    • Avoid duplicating DTO definitions between frontend and backend.
    • Use ESM-compatible and tree-shakable libraries.
    • Support const-style enums and branded types.

    Is there a way to achieve this without compromising validation or type safety?

    Continue reading...

Compartilhe esta Página