This video is available to students only

Typing Functions with TypeScript

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

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.

Start a new discussion. All notification go to the author.