TypeScript came to make it easier for developers to work. This JavaScript superset has very useful tools. Let's learn about types in functions.
We have the example below that has a simple function that returns a name:
const myAge: number = 21
const myName: string = 'Raphael'
function returnName(): string {
return myName;
}
Well we have two variables. One is of type number and the other is of type string.
But what is the returnName function getting for a type? Any? When we put the pointer over the function, we get this result:
TypeScript infers, this function is now of type string, because of the variable it is returning (let myName). So if you pass the return myAge, yes, the function will be of type number.
But what if I want my function to return only a specific type? In this case in our code we will see how it would look:
const myName: string = 'Raphael'
function returnName(): string {
return myName;
}
Now that our function is only returning string, it only accepts receiving string types so if you try to pass a variable of type number, boolean it will return this error:
The error helps to understand the problem, number is different from the string type, so it will never be possible in this case.
But a question arises, if I pass to any const myName: any = 'Raphael'
, will TypeScript also report this problem? If you already have experience developing with TypeScript the answer is clear, but let's see what happens:
No problems detected, because any cancel the type check. In other words, we will never have a problem if the const is 'any' type, but we want to avoid type 'any'. This example was just to understand the behavior of typescript.
Let's understand now how to pass types in the parameters.
It is very common to pass parameters to our functions. In TypeScript we can define types for the parameters, see another example:
function multiplyNumbers(x, y) {
return x * y
}
console.log(multiplyNumbers(2, 2))
The result on the broswer console is 4, but look at this warning we received from TypeScript:
Note this is not an error! It's just a warning. The parameters were set to any. If you compile you will see that it works normally! But we want to make the most of the power of TypeScript, so let's now define types for the function as well as for the parameters:
function multiplyNumbers(x: number, y: number): number {
return x * y
}
console.log(multiplyNumbers(2, 2))
It is possible to set the warning: parameter 'x' implicitly has an 'any' type to never appear, just set the flag "noImplicitAny": true, in the tsconfig.json file to false, but I do not recommend doing this. I believe that warning are very useful.
Thank you if you read this article until the end! I hope that the information on has been passed on clearly. If you want to contribute, please leave a comment with a suggestion.
See you on the next post.