Reputation: 21
I'm curently learning Typescript and I'm having an issue ...
Type assignation for a function
Here are 2 simple sample of code, which are compiling in a different way and I don't get the reason.
1 Sample
testP(): Promise<number> {
return new Promise<string>((resolve, reject) => {
resolve("string");
});
}
This code returning in error during compilation as I'm not returning a number, that's fine.
2 Sample
testP(): Promise<number> {
return new Promise<any>((resolve, reject) => {
resolve("string");
});
}
This code is compiling without any bug and I don't know why ...
WHat is my mistake ? Thank you in advance !
Edit:
Here is what I'm actually trying to do
export interface Animal {
name: string,
weight: number,
age: number
}
getDogs(): Promise<Dog[]> {
return this.http.get('/dogs')
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
But like that, even if my "response" is not an array of "dogs", it doesn't trigger any error;
What am I missing ?
Upvotes: 2
Views: 189
Reputation: 23682
The compiler cannot infer the return type of the promise from a call to resolve
.
This code:
return new Promise((resolve, reject) => {
... is a shorthand for:
return new Promise<any>((resolve, reject) => {
And then the type any
is a way to disable type checking. Your second code compiles but it is wrong.
If you don't want to repeat yourself, you can do this:
let testP = function () {
return new Promise<string>((resolve, reject) => {
resolve("string");
});
}
Here, the return type of the function is inferred to Promise<string>
.
EDIT #1 (To answer to your answer): Promise<any>
is compatible with Promise<number>
, and "string"
is also compatible with any
. But Promise<string>
is not compatible with Promise<number>
. In fact, any
allows you to do wrong code. When you use it, it's up to you to know what you are doing.
EDIT #2:
About this code:
export interface Dog {
name: string,
weight: number,
age: number
}
function getDogs(): Promise<Dog[]> {
return this.http.get('/dogs')
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
The TypeScript compiler checks types statically. It can't check the type of a string value returned by the server, because, at run time, on the browser, there is just compiled code without types metadata at all.
TypeScript is like JSDoc. It helps to describe parts of your program. It can't help to check data that your program receives dynamically.
Upvotes: 3