typestack/class-transformer

feature: Add type checking for data passed to

scotch83 opened this issue · 3 comments

Description

add type checking to the method signature using Partial<T> for the plain object to be transformed.

The plainToClass method signature can be improved using the Partial utility type in Typescript to give autocomplete feature when passing objects to transform as the second parameter.

Thanks for reconsidering this feature request, if you need help I can work on it and propose a PR.

Proposed solution

function plainToClass<T>(
  ctor: new (...args: any[]) => T,
  obj: Partial<T>
)

Hello @scotch83,

this signature would assume you do not use renaming in @Expose, which would not be in the Partial<T> type. Also using custom transformers you could have T and plain completely different types.

Example:

class User {
   @Expose({name: 'fullName'})
   name: string;

   @Transform(({ value }) => moment(value), { toClassOnly: true })
   dateOfBirth: Moment;
}

const plain = {
  fullName: 'username',
  dateOfBirth: '2000-01-01'
}

The type checking you suggest would not work in most of the use cases of this library.

If you are in a codebase that uses the library the way that the class type always matches the plain, you can override the plainToClass function and add this type signature for you project.

Note: use plainToInstance, as plainToClass is deprecated!

I close this as invalid. If you have any questions left feel free to comment on this issue.

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.