You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When creating a complex object, it's sometimes desirable to use plainToClass with an inline object literal. Unfortunately, the plain object will not be type checked:
classUser{name: string;age: number;constructor(name: string,age: number){this.name=name;this.age=age;}}// no error for missing age, badconstuser1=plainToClass(User,{name: 'test',});
One way to do type checking is to provide the type explicitly. But you have to type the class name 3 times to get this to work:
// error, good but verboseconstuser2=plainToClass<User,User>(User,{name: 'test',});
As @lazarljubenovic mentions, this only works until you are not renaming properties, in that case the two type would not match and you wouldn't be able to call plainToClass. What would be cool to infer the classToPlain return type but I am not aware of any way to do that with Typescript.
I will close this as this is not possible I believe, but I will keep my eyes open for any such thing in the future as I believe automatic type inferring is a very useful feature.
Description
When creating a complex object, it's sometimes desirable to use plainToClass with an inline object literal. Unfortunately, the plain object will not be type checked:
One way to do type checking is to provide the type explicitly. But you have to type the class name 3 times to get this to work:
Proposed solution
In my projects, I added a helper function:
(I'm not sure about the name. It could be made clearer)
Now you get proper type checking without repeating the class name:
The text was updated successfully, but these errors were encountered: