class-transformer
class-transformer copied to clipboard
docs: add example of array with different types
Description
Add usage examples of array with different types, using the @Transform()
decorator.
Checklist
- [x] the pull request title describes what this PR does (not a vague title like
Update index.md
) - [x] the pull request targets the default branch of the repository (
develop
) - [x] the code follows the established code style of the repository
-
npm run prettier:check
passes -
npm run lint:check
passes
-
- [ ] tests are added for the changes I made (if any source code was modified)
- [x] documentation added or updated
- [x] I have run the project locally and verified that there are no errors
Fixes
Hi @mrbrunelli
Is it possible to use @Transform
for String, Number or Boolean?
There are some use cases I need to user @Transform
such as:
Trim lowercase email
class User {
email: string[];
}
const user = {
email: [
"[email protected]",
"[email protected]",
" [email protected]"
]
}
const cleanEmailsUser = plainToInstance(User, user);
Expect: I wanna use @Transform
like
class User {
@Transform(({value}) => lowercase(value.trim) ) // This transform apply for each email string in email list
email: string[];
}
const user = {
email: [
"[email protected]",
"[email protected]",
" [email protected] "
]
}
const cleanEmailsUser = plainToInstance(User, user);
Expect:
/**
*{
* email: [
* "[email protected]",
* "[email protected]",
* "[email protected]"
* ]
*}
*/
Received: I tried but @Transform
is not trigger at all
Any way to use @Transform
that way
Thank you
Hi @tonynguyenit18.
You need to iterate value
when it's an array. For boolean values, you only need to return an expression.
class User {
@Transform(({ value }) =>
value.map((item: string) => item.trim().toLowerCase())
)
emails: string[]
}
I created this example for you: https://github.com/mrbrunelli/class-transformer-example/blob/main/src/transform-array.spec.ts
Hi @mrbrunelli,
I think your example implements the 'discriminator object' feature but using Transform instead of Type. Read more.