Beginner's TypeScript Tutorial (18 exercises)
Problem

Function Return Type Annotations

Continuing from last time, we have a User that includes an array of posts.

This time instead of having a defaultUser, we instead have a makeUser function that should return a user.

At this current starting point, the function is returning an empty object.

Because our test code is expecting a User, TypeScript is showing us errors.

Experiment with makeUser's return

Add some keys and values to the object returned from makeUser. When you hover over the call to makeUser() in the test, you'll see a popup that shows what would be returned from the function:

You don't have to specify what a function returns.

Challenge

Similar to a previous challenge, we want TypeScript to show us error messages on the lines where they happen instead of in a test.

Your challenge is to annotate the makeUser function to make sure it always returns a User.

Transcript

We've got a similar problem here to what we had before. We've got our User, which is using Array of Posts, which has the Post here, and we've got a makeUser function. Instead of doing a default user, we're now just returning this makeUser function here.

Inside here is supposed to represent a user, except we've got a bunch of errors down here. What it's saying is that the function, or the thing that gets returned from makeUser, which is this, is just an empty object.

If I add some stuff in here and say blah, blah, blah, blah, then it's going to grab that and put it there. This is a pretty good lesson in itself, is that you don't need to say to TypeScript what a function returns.

In this case, it's going to be pretty nice to ensure that makeUser always returns a user, very similar to the problem we had before, where we wanted to make sure that the error message was on the correct line.

Here we've got lots of error messages, and they're all pretty confusing and fairly hard to understand. How do we annotate our function to make sure that makeUser always returns a user?