Class-transformer: Feature request: plainToClass with discriminator

Created on 6 Jan 2019  路  4Comments  路  Source: typestack/class-transformer

Is it possible for me to have a plainToClass(Vehicle, v) call return either a Car class or Train depending on it's type property? I know this is similar to discriminator in @Type. I don't like having to create a wrapper class just to harness that ability:

class Wrapper {
  @Type( () => Vehicle, {
    discriminator: {
      property: 'type',
      subTypes: [
        {value: Car, name: 'car'},
        {value: Train, name: 'train'},
      ],
    },
  })
  vehicle: Car | Train;
}

const w = plainToClass(Wrapper, { vehicle: { type: 'car' } });
const v = w.vehicle;
v.doSomething();

Most helpful comment

I'm not having that problem, I am simply asking for the ability to take a plain object and turn it into an instance of a class based on the type property without needing to use a wrapper class. But yeah Vehicle is an abstract class. It's not a super important thing but it would be nice.

All 4 comments

even though according to the documentation the above example should work, I was having issues with this too.

Is Vehicle an abstract class that is extended by Car and Train?
I was having a similar issue and needed to replace the first argument abstract class with generic Object to make it work;

Like so:

class Wrapper {
  @Type( () => Object, {
    discriminator: {
      property: 'type',
      subTypes: [
        {value: Car, name: 'car'},
        {value: Train, name: 'train'},
      ],
    },
  })
  vehicle: Car | Train;
}

I'm not having that problem, I am simply asking for the ability to take a plain object and turn it into an instance of a class based on the type property without needing to use a wrapper class. But yeah Vehicle is an abstract class. It's not a super important thing but it would be nice.

Hey @patricknazar, I've had a read through the code and can't see any way of using polymorphism directly on the root object being sent to plainToClass(). It looks like the polymorphism features only work for nested values in an object.

I reckon it would be more appropriate to retitle this issue as a feature request, rather than a question.

I think PR #175 solves this, it's not merged yet though.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

leon19 picture leon19  路  5Comments

AckerApple picture AckerApple  路  5Comments

ERPedersen picture ERPedersen  路  4Comments

braivre picture braivre  路  3Comments

NoNameProvided picture NoNameProvided  路  5Comments