typestack / class-transformer

Decorator-based transformation, serialization, and deserialization between objects and classes.
MIT License
6.86k stars 502 forks source link

fix: plainToClass on a sub-class ignores the @Type-decorators in the parent class. #876

Open elr0berto opened 3 years ago

elr0berto commented 3 years ago

Description

If you run plainToClass on a class that extends a class that has @Type-decorators for nested classes plain to class fails to transform the nested classes into class instances and just leave them as plain objects.

Minimal code-snippet showcasing the problem

class Nested {
 foo: string;
 Print() {
    console.log("hello!");
  }
}
class Parent {
   @Type(() => Nested) 
   nested: Nested;
}
class Child extends Parent {
}

let plain = {
   nested: {foo: "foo!"}
}

let child = plainToClass(Child, plain);
child.nested.Print(); // function does not exist.

Expected behavior

I expect child.nested to be an instance of "Nested"

Actual behavior

child.nested is a plain object. trying to call class methods crashes with function is not defined.

yaronEcoPlant commented 2 years ago

It's an issue we also have, something broke since v0.3.2.

One way to solve this (temporary of course), is to do plainToClass(t, v, {enableImplicitConversion: true});

RaymsDev commented 2 years ago

Have you tried with the @Expose() decorator ?

v1jayr commented 1 year ago

I am having the same issue. Unable to invoke methods defined in nested object. Getting undefined is not a function

thirtified commented 7 months ago

I find it a bit surprising that this issue is still open and unresolved – the ability to handle nested properties seems quite fundamental? The enableImplicitConversion workaround unfortunately didn't work for me and I had to fall back to using a different conversion mechanism. Would be great to be able to use class-transformer for this as well!