Beginner's TypeScript #8

nhannguyendevjs

Nhan Nguyen

Posted on December 25, 2023

Beginner's TypeScript #8

Image description

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 have a makeUser function that should return a user.

const makeUser = () => {
  return {};
}
Enter fullscreen mode Exit fullscreen mode

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

We will figure out how to annotate the makeUser function to ensure it always returns a User.

👉 Solution:

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

In this case, we will add : User since we want to return a User.

Before:

const makeUser = () => {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

After:

const makeUser = (): User => {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

Specifying the type a function returns will check our code as we write it.

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

Notice that if we do not 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 us to be more strict in ensuring that our function is safe on the inside as well as the outside.

✍️ Experiment Without the Return Type:

If we 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 is impressive about it is that it infers the types based on what is present in the return object. Even if we comment out the User, TypeScript will show information about each of the object's properties.


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

💖 💪 🙅 🚩
nhannguyendevjs
Nhan Nguyen

Posted on December 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Beginner's TypeScript #tips
programming Beginner's TypeScript #tips

January 24, 2024

Beginner's TypeScript #27
programming Beginner's TypeScript #27

January 19, 2024

Beginner's TypeScript #26
programming Beginner's TypeScript #26

January 18, 2024

Beginner's TypeScript #25
programming Beginner's TypeScript #25

January 17, 2024