Dmo
Dmo

Reputation: 25

Nest js union dto types

I have a nestjs dto classes. Use it for response dto.

class A {
  response: '1', 
  prop1: string
}
class B {
  response: '2', 
  prop2: string
}

Everything works

function foo ():A|B {
  const result:A|B = bar();
  if (result.response === '1') {
    // get result.prop1
  }
}

Is it possible to union A and B classes in C? So we not need to union it in foo function.

Looked in https://docs.nestjs.com/openapi/mapped-types, but there is no union type.

Upvotes: 0

Views: 38

Answers (1)

Motunrayo Koyejo
Motunrayo Koyejo

Reputation: 427

NestJS does not natively support union types for response DTOs. However, you can create a discriminated union type in TypeScript for A and B within a new class C, allowing you to avoid manually writing the union in foo().

type C = A | B;
function foo(): C {
  const result: C = bar();
  if (result.response === '1') {
    console.log(result.prop1); // TypeScript understands `result` is `A`
  }
}

Upvotes: 0

Related Questions