0

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.

1 Answer 1

0

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`
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.