Class-transformer: Typescript error converting a single plain object to a Class

Created on 25 Jul 2016  路  3Comments  路  Source: typestack/class-transformer

Hi,
I tried this library and played a little with your example. My configuration is the following Angular1 + typescript + webpack. I installed your library into my project with npm.

In your example, in users.json, you are returning an array of user objects. To my need, I returned only one user object. I then wrote a service like this one :

export class UserService {

  constructor(private $http: ng.IHttpService) {}

  getUser(): ng.IPromise<User> {
    return this.$http
      .get('assets/user.json')
      .then((response: any) => response.data)
      .then((response: any) => {
        let user = plainToClass(User, response);
        console.log('user', user);
        return user;
      });
  }
}

I have the following error in my console :

ERROR in ./src/app/services/user/user.service.ts
(9,12): error TS2322: Type 'IPromise'.
Type 'User[]' is not assignable to type 'User'.
Property 'id' is missing in type 'User[]'.

The code is working because I can see the console.log and have the right values. But this error prevents me from building the code. The problem is that in the npm package, I have an index.d.ts and the plainToClass is pointing to the array version instead of the single object, i.e.

export declare function plainToClass<T, V extends Array<any>>(cls: ClassType<T>, plain: V, options?: ClassTransformOptions): T[];

instead of

export declare function plainToClass<T, V>(cls: ClassType<T>, plain: V, options?: ClassTransformOptions): T;

PS : I have the 0.1.0-beta2 version installed.

Most helpful comment

Can you try to do it this way:

let user = plainToClass(User, response as Object);

All 3 comments

Can you try to do it this way:

let user = plainToClass(User, response as Object);

Based on your answer I wrote it like this to make it work.

getUser(): ng.IPromise<User> {
    return this.$http
      .get('assets/user.json')
      .then((response: any) => response.data)
      .then((response: Object) => {
        let user = plainToClass(User, response);
        console.log('user', user);
        return user;
      });
  }

Cheers !

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ceopaludetto picture ceopaludetto  路  3Comments

AckerApple picture AckerApple  路  5Comments

SC30SC picture SC30SC  路  4Comments

ERPedersen picture ERPedersen  路  4Comments

gregsolo-intent picture gregsolo-intent  路  5Comments