This video is available to students only

Typing Functions with TypeScript

In this lesson, we're going use TypeScript with the functions

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

Using TypeScript with functions#

In this lesson, we'll see how to use TypeScript with functions. For that, let's create a new file again and let's call it functions.ts. Inside the file, let's create a function, sum, which accepts two numbers and adds them. We have seen that we can assign types to the parameters, but if we hover over the function, you see type number which is the return type of the function. TypeScript knows that if two numbers are added, it will yield a number, so TypeScript has inferred the return type. If we change them to string and hover over it again, the return type changes to string. TypeScript is smart enough to handle that.

If you want a specefic return type, you can mention the return type after the parameters bracket. Now if I put the return type to be a number, it will show us an error because TypeScript is expecting number to be returned, so let's remove string type, and the error is gone. Although you can choose to write your return type, but in straightforward functions like this one, it's better to let TypeScript do its job by simply inferring it.

If function is expecting the return type to be a promise, which involves making an API request and then returning the data, it's better to explicitly define the return type.

We also have a use case where the function doesn't return anything. In other programming languages, it's called void and we create a function, printMe, to just console log "Print me". Now let's hover over it. We see void as the return type. JavaScript doesn't understand it but TypeScript and almost all other programming languages do. Now, if you explicitly place the return type to be void and return something, let's say a number 5, it will complain because it's expecting nothing to be returned. I hope this concept is clear.

This lesson preview is part of the The newline Guide to Fullstack ASP.NET Core and React course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to The newline Guide to Fullstack ASP.NET Core and React with a single-time purchase.

Thumbnail for the \newline course The newline Guide to Fullstack ASP.NET Core and React