TypeScript Unlocked: Functions

TypeScript Unlocked: Functions

💡
This article is a part of TypeScript Unlocked Series on my blog. Every article in the series is short, crisp and filled with examples and code snippets. If you want to learn TypeScript from scratch for absolutely FREE!!! check it out.

Function Anatomy for typescript

Looking at the above image you can see how we do type checking when we write a function. If you don’t specify any type for the function parameter or function return type it will default to type of any which is not recommended when using type script.

Understating how types work in functions

If you have understood how the type checking is done for a variable understanding this will be very simple. Lets see how the types work in function.

Parameter type

when you specify the parameter type typescript will warn you if you try to perform operation on that particular parameter which is outside the scope of its type. for example if you have specified the type as number and you are trying to apply string methods on the parameter you’ll get a red line.

Return type

when return type of a function is specified, you can’t return a value from the function which is other than the specified type. for example you cant return a string if you have specified the return type as a number.

Arrow Function Anatomy for TypeScript

Every functionality remains the same expect the minor syntax changes

Using types in map or any call back function

it’s the same syntax we use for arrow function with only difference that the function is being placed inside another function.

actually it’s not required to specify the type when we are using the map function because TypeScript is smart enough to know the type value we’ll be having for the parameter by reading the array on which we are using the map.

if you don’t specify the type and hover over the variable you can see that it already knows what type is it (I'm using VS code).

Never Type

We use never when we want to specify that the function should not return anything not even void. This is helpful when we want to call the function which terminates our program or just raises and error.

function rainsError(errMsg: string): never{
    throw new Error(errMsg);
}

if you reached till here and you liked what you read don't forget to share it with other people. if you have any feedback or suggestions feel free to use the comment section. Hope you tag along till the end of this series and strengthen your coding armor by adding TypeScript to it. Happy coding!