I'm hoping to use class-tranformer / class-validator to convert form values to the correct typings in my UI. It works in my server applications but does not work in React. Can someone help ?
import { plainToClass } from "class-transformer";
import { IsNumber } from "class-validator";
import "reflect-metadata";
export class LovelyObject {
@IsNumber()
//@ts-ignore
public shouldBeANumber: number;
}
const worksIfNotInReact = plainToClass(
LovelyObject,
{ shouldBeANumber: "234" },
{ enableImplicitConversion: true }
);
Expected Output (working in server applications)
{"shouldBeANumber" : 234}
Output in ReactJS
{"shouldBeANumber" : "234"}
This code works fine here : https://codesandbox.io/s/workshere-c4wek?file=/src/index.ts:0-341
But does not work in context of a react application : https://codesandbox.io/s/not-working-q80uy?file=/src/App.tsx
Well, React has nothing to do with it. Most likely your environments are different, i.e. how you're importing reflect-metadata shims.
@sebastian-zarzycki-es I'll look into it. As far as I'm aware I was doing it in the same manner.
I've seen some posts suggesting Babel might be stripping out the types in CRA.
Ah, React... about the only tool that has a CLI with a custom name, because CLI is not hipstery enough...
Adding babel-plugin-transform-typescript-metadata to the babel plugins does the job. Thanks for steering me in the right direction @sebastian-zarzycki-es
Would you mind posting the required config here? I am not familiar with Babel, but this topic came up multiple times so we should add it to the README.
https://github.com/leonardfactory/babel-plugin-transform-typescript-metadata
{
"plugins": [
"babel-plugin-transform-typescript-metadata",
...
],
...
}
Was enough to get the functionality I required.
Thanks!
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.