Search code examples
reactjsclass-validatorclass-transformer

class-tranformer / class-validator with enableImplicitConversion not working as expected in ReactJS


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


Solution

  • Adding babel-plugin-transform-typescript-metadata to the babel plugins does the job.