0

I am trying to create my own "Mapped types", for the swagger dto in nestJS.

In the official document there are many "Mapped types". But, I need to add all the fields of a class, and make ONLY SOME as optional.

For which, I do something like this:

export default class CreateUserDto extends IntersectionType(
  OmitType(UserDto, ['nickname'] as const),
  PartialType(PickType(UserDto, ['nickname'] as const)),
) {} 

This works perfectly. All fields are added, but only nickname as optional.

But, it is not very practical to reuse. So I would like to create a custom class to be able to extend it and have the same result.

I try the following:

const OptionalType = (dto, optional) => {
  return class NewClass extends IntersectionType(
    OmitType(dto, optional as const),
    PartialType(PickType(dto, optional as const)),
  ) {};
};

export default class CreateUserDto extends OptionalType(UserDto, [
  'nickname',
]) {}

And directly returning "IntersectionType" without creating a class.

But this didn't work.

When I try to use the "optional" variable I get the error... "A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals."

Could you guide me on how to achieve what I want? please

1 Answers1

0

You don't need to add the as const to the optional inside the OptionalType, you'd only need to add it to when you invoke OptionalType.

e.g.

const OptionalType = (dto, optional) => {
  return class NewClass extends IntersectionType(
    OmitType(dto, optional),
    PartialType(PickType(dto, optional)),
  ) {};
};

export default class CreateUserDto extends OptionalType(UserDto, [
  'nickname',
] as const) {}
Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • The swagger in nestJS is not generating the output I need, but, your answer solves the original problem in my post, thank you very much! – Andreina Riera Oct 11 '22 at 01:51