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.
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.
Most helpful comment
Can you try to do it this way: