Beginner's TypeScript Section 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:


const makeUser = () => {

After:


const makeUser = (): User => {

Specif

Loading solution

Transcript

0:00 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.

0:17 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.

0:36 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.

0:54 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.

1:11 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.