plainToClass assumes response is an array
See original GitHub issueGiven the following code:
getProposal(id: string) : Promise<Proposal> {
const url = `${this.proposalsUrl}/${id}`;
var headers = new Headers();
this._authService.createAuthorizationHeader(headers);
var options = new RequestOptions({ headers: headers });
return this.http.get(url, options)
.toPromise()
.then(response => plainToClass(Proposal, response.json()));
}
I get the typescript error:
[ts] Type ‘Promise<Proposal[]>’ is not assignable to type ‘Promise<Proposal>’. Type ‘Proposal[]’ is not assignable to type ‘Proposal’. Property ‘id’ is missing in type ‘Proposal[]’.
How did it conclude that the response is an array??
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:5 (1 by maintainers)
Top Results From Across the Web
Exposing an array of object using class-transformer
I am not able to expose an array of objects. The Followers array is not getting exposed, even though I exposed in the...
Read more >Handling date fields in JSON with Typescript | by Doron Tohar
When we call plainToClass(T, a) and a is an array of type T[] , it knows to map each element as class T...
Read more >Serialization | NestJS - A progressive Node.js framework
Let's assume that we want to automatically exclude a password property from ... When this endpoint is requested, the client receives the following...
Read more >Type-transformer - npm.io
You want to have an array of object of type Person , however, you only get plain objects: fetch('persons.json').then((response:Response) ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
You are having this issue because Typescript does not know the type of
response.json(). This is becauseplainToClass(and some other methods fromclass-transformer) has multiple signatures. Fromsrc/index.ts:Since Typescript cannot determine the appropriate signature, I assume it just picks the first one, hence why it’s telling you that
Proposal[]is expected.To fix your problem, you simply need to explicitly declare the type of
response.json()usingas Proposal:And off you go 😃
To array:
To single:
^-- a little less redundant.