Comments (4)
Thank you for the detailed explanation. This helps!
Best regards :)
from class-transformer.
Hi @andreasvh-conceto,
Thank you for the detailed issue and sorry for a late reply.
The error you got is a typescript error and nothing to do with this library.
The error clearly states that 'Types of property 'photos' are incompatible.' You used the Partial<AlbumDto>
, but AlbumDto contains 'photos: PhotoDto[]', which is not Partial, so when you instantiate with an object containing photos
, it will require you to be compatible with 'PhotoDto'. (so Partial is not a deep Partial).
But this is not the way you would want to use class-transformer
. Here is a snippet for your scenario which will work:
class AlbumDto {
id: number;
name: string;
@Type(() => PhotoDto)
photos: PhotoDto[];
@Expose()
get title(): string {
return "My super album";
}
}
class PhotoDto {
@Expose()
filename: string;
@Expose()
get author(): string {
return "John";
}
}
describe("transmission detail response dto serialization test", () => {
it("learning test nested objects", () => {
const albumPartial = {
id: 1,
name: "My Album",
photos: [{ filename: "photo1.jpg" }, { filename: "photo2.jpg" }],
};
const album = plainToInstance(AlbumDto, albumPartial);
expect(album.id).toEqual(1);
expect(album.name).toEqual('My Album');
expect(album.photos[0].filename).toEqual('photo1.jpg');
expect(album.photos[1].filename).toEqual('photo2.jpg');
expect(instanceToPlain(album)).toEqual({
id: 1,
name: 'My Album',
photos: [
{ filename: 'photo1.jpg', author: 'John' },
{ filename: 'photo2.jpg', author: 'John' }
],
title: 'My super album'
});
});
});
from class-transformer.
Hi @diffy0712
one question came into my mind, while playing around with your answer. When i choose to @Expose({name: "myPropertyName"})
the plainToInstance
method returns undefined for the annotated property. Currently i handle that using the ignoreDecorators: true
option like this:
const album = plainToInstance(AlbumDto, albumPartial, {
ignoreDecorators: true, // this prevents that the property will be undefined, since it is keeping the property name from the created instance
});
Is this the right approach to go for?
Thanks a lot and best regards
from class-transformer.
Hello @andreasvh-conceto,
if you provide @Expose({name: "myPropertyName"})
decorator to the name
property, when calling plainToInstane
, it will expect your plain to have a property called 'myPropertyName' instead of the real property name
, which I assume you did not provide in your plain object, so it was set to undefined.
I would not suggest to use ignoreDecorators
for this, as it is the same as not using the decorator in your situation.
So updating my previous example:
// if you add
@Expose({name: "myPropertyName"})
name: string;
// then you plain would needs to change to
const albumPartial = {
id: 1,
myPropertyName: "My Album",
photos: [{ filename: "photo1.jpg" }, { filename: "photo2.jpg" }],
};
NOTE: if you override the name in expose, then you will get that name in your instanceToPlain
result as well. If you need to override name only on one way please use the options toPlainOnly
or toClassOnly
. @Expose({name: "myPropertyName", toClassOnly: true})
Please read the documentation a bit more in detail, because everything I have wrote here is already in the documentations!
Hope this helps.
from class-transformer.
Related Issues (20)
- question: Getting `ReferenceError: Cannot access 'XXX' before initialization` in class circular dependency with Jest & Typescript HOT 3
- question: Constructors validation seems to break when using plainToInstance HOT 3
- Include @IsOptional values to the body if they are missing with default value HOT 2
- fix: Can't use instanceToPlain with Nitro.js event. HOT 4
- External Values are not stripped. HOT 4
- fix: plainToClass cannot handle URL values HOT 6
- feature: function support of options.discriminator.subTypes HOT 2
- plainToClassFromExist is Deprecated what is the replacement for generics? HOT 2
- Cannot transform string to number HOT 7
- question: Is class-transformer really thought to be used in the backend? HOT 4
- question: Options in @Transform Decorator Do Not Reflect Those Passed to plainToInstance in class-transformer HOT 2
- question: Casting Json to the required datatype HOT 2
- instanceToPlain not working properly using nestjs HOT 3
- Transform decorator in class-transformer does not wait for asynchronous function and returns a Promise instead of the transformed value HOT 3
- fix: Expose not working correctly with toClassOnly HOT 1
- fix: bug in casting boolean properties from `@Query()` in Nest.js HOT 3
- fix: Unable to use "name" as a property in class-validator HOT 1
- fix: No Capability to BigInt? HOT 1
- fix: JSDoc comments do not automatically apply to overloads
- fix: incorrect property name in validation messages when using @Expose()
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from class-transformer.