class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

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

Open elr0berto opened this issue 4 years ago • 4 comments

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.

elr0berto avatar Aug 12 '21 14:08 elr0berto

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});

yaronEcoPlant avatar Dec 14 '21 16:12 yaronEcoPlant

Have you tried with the @Expose() decorator ?

RaymsDev avatar Jun 27 '22 15:06 RaymsDev

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

v1jayr avatar Jan 15 '23 18:01 v1jayr

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!

thirtified avatar Apr 03 '24 07:04 thirtified