Open
Description
Given 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'.
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??
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
gempain commentedon Oct 10, 2017
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 :)
rightisleft commentedon Mar 27, 2018
While that works - it seems a bit redundant?
davidquintard commentedon Mar 11, 2019
Hi there,
What about this issue?
DimiTech commentedon Apr 23, 2019
Hello, I'm interested in this as well! Thanks!
jasperblues commentedon May 27, 2019
To array:
To single:
^-- a little less redundant.
Edit: Just came here in 2024 and chose one of the higher in the thread (and slightly redundant) answers, not realizing I'd found a better way in 2019 :D