typestack/class-transformer

feature: function support of options.discriminator.subTypes

buddh4 opened this issue · 3 comments

buddh4 commented

Description

We currently can define discriminator types as follows:

@Type(() => Photo, {
    discriminator: {
      property: '__type',
      subTypes: [
        { value: Landscape, name: 'landscape' },
        { value: Portrait, name: 'portrait' },
        { value: UnderWater, name: 'underwater' },
      ],
    },
  })
  topPhoto: Landscape | Portrait | UnderWater;

This assumes that we know all subTypes at build time. There is no way (I've found) to add discriminator types at runtime (other that passing the subTypes array around).

Furthermore the transformer throws an error when using instanceToClass and the discriminator is not contained in the subTypes. Maybe a strict or fallbackToDefault configuration would be nice.

Proposed solution

It would be great if you could also use a function for the subType option as follows:

@Type(() => Photo, {
    discriminator: {
      property: '__type',
      strict: false,
      subTypes: (subType: string) => getTypeOfPhoto(subType),
    },
  })
  topPhoto: Landscape | Portrait | UnderWater;

I'm happy to contribute in case this feature is desired. I did a quick look and it seems this would only require minor changes here and here.

Hello @buddh4,

could you please give some use cases for dynamic subTypes? I assume getTypeOfPhoto would do the same as the map, isn't it?
I am not sure when this would be useful.

Thank you

Closing as invalid, because of inactivity.
If you want to continue this discussion, feel free to comment on this issue.

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.