nest-dto
nest-dto copied to clipboard
picked type does not work with class-transformer
Suppose there is type:
class Foo {
@IsString()
bar!: string;
@IsString({
optional: true,
})
baz?: string;
}
and then we use the pick
method to create a subset type:
const NewFoo = pick(Foo, 'NewFoo', ['bar']);
And then we extend NewFoo:
class MyFoo extends NewFoo {
@IsString()
baz!: string;
}
If you use class-transformer (or @hippo/safari-validation
) to create MyFoo
from a plain object, it will not include baz
in the class instance:
const myFoo = toClassSync(MyFoo, { bar: '123', baz: 'abc' });
console.log(myFoo);
// { bar: '123' }
The way to work around this is to also pick baz
into NewFoo
, and then overwrite baz
in MyFoo
. I am not sure why this is the case, and it only happens if the field has the same name as a field on Foo
. This seems to have started since the last release (0.18.0).
There are some limitations in the pick implementation that might be showing up here. I vaguely remember documenting some of the details, but the gist is that the metadata used by the transformer and validator libraries are hidden from us such that we can only really get away with adding new decorators (e.g. nullability) on top of exist field definitions, rather than truly overwriting definitions. This limitation can cause some weird outcomes.