2

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 ?

8
  • 1
    You don't mean assignation. You might mean assignment. Commented Oct 7, 2016 at 9:33
  • Never used Typescript, but I guess there's no way for the interpreter to know that your promise won't resolve as a number, so it assumes it'll be fine Commented Oct 7, 2016 at 9:33
  • @floribon: The question is about the TypeScript compiler. Commented Oct 7, 2016 at 9:36
  • What version of typescript are you using? I don't see any errors in typescript playground. Commented Oct 7, 2016 at 9:41
  • 1
    What's the difference between your two samples? My eyes aren't that good. Commented Oct 7, 2016 at 13:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yea you're completly right, it's a compiler so there is no way it can check the types of datas provided by a server ... So here is my last question (I hope !). In the Angular2 tutorial, they're using the type checking on a promise: angular.io/docs/ts/latest/tutorial/toh-pt6.html (in the function: getHeroes). Is this just like a code comment then ? Thanks a lot for the time you used to answered me !
They use a type assertion: response.json().data as Hero[]. It is a way to say to the compiler: "Trust me and consider that the object response.json().data is of type Hero[]". Yes, it is "like a JSDoc" here, too.
Now I get it ! Sorry, Typescript is really new to me and I'm still not really confident with it. However, your explanations were really clear so thank you a lot once again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.