Beginner's TypeScript Tutorial (18 exercises)
solution

Annotate a Function to Specify its Return Type

The solution is to add a colon and the type you want to return after the parentheses when the function is defined.

In this case we'll add : User since we want to return a User.

Before:

After:

Specifying the type a function returns will check your code as you write it.

For example, User expects id to be a number. If you pass it a string, TypeScript will show you the error inside of the return object right away.

Notice that if you don't include everything that User expects, the errors all show within the makeUser function where the errors are instead of in the tests at the bottom of the file.

Adding type return annotations allows you to be more strict in ensuring that your function is safe on the inside as well as the outside.

Experiment Without the Return Type

If you erase the : User from the makeUser function declaration, hovering over the function in VS Code will display a preview of what the function returns.

What's impressive about it is that it infers the types based on what's present in the return object. Even if you comment out the User, TypeScript will show information about each of the object's properties.

Transcript

The solution here is this syntax. This syntax allows you to specify what a function can return. For instance, if I make a mistake here and accidentally parse a string instead of a number, then it's going to yell at me because string is not assignable to type number.

Now even if I get this wrong inside here, then actually this stuff is still going to be OK. Because I've said that make user always returns a user. anytime that you actually create a user, TypeScript is going to say, "OK. Yeah. I understand that. You've created a user." but it's going to yell at you closer to the call site.

Which is great, which means we get auto completes at the call site, which means I can parse an array of posts, a role, which of course is super admin, and it means that since you don't always need to add this, by the way. If I remove this, then TypeScript is still going to understand everything.

Although it actually drops a couple of things, because it's not understanding that this can contain a number and title can contain blah, blah, blah, blah, blah. It's actually pretty impressive that TypeScript is able to understand this. You can actually hover over it to see what a function returns.

You see that it's inferred all of this information. We can even delete all of this stuff up here or comment it out. TypeScript will understand what our makeUser function is returning, and it won't yell at us down here. Sometimes you want to be a little bit stricter, and sometimes you just want to be able to specify, "OK, this returns a user. That means that my function here is going to be safe on the inside as well as the outside." This syntax here is extremely useful.