Chuck's Academy

Basic TypeScript

Functions in TypeScript

Functions are one of the fundamental pillars in any programming language, and TypeScript adds typing to make functions more secure and predictable. In this chapter, we will learn how to type parameters, return values, and how to handle optional functions and default parameters.

Typing Parameters and Return

In TypeScript, you can specify the type of parameters a function receives, as well as the type of value it returns. This ensures that the function is used correctly and that its behavior is predictable.

Example of Typing Parameters and Return

typescript
"This function called add takes two parameters, a and b, both of type number. The function returns a number which is the sum of both."

If you try to pass values that are not numbers, TypeScript will generate an error:

typescript
"This example shows that if you try to pass a string instead of a number, TypeScript will warn you that there is a type error."

Optional Parameters

Just like with optional properties in objects, TypeScript allows function parameters to be optional. This is achieved by adding the symbol ? after the parameter name.

Example of Optional Parameters

typescript
"In this example, the greet function has an optional parameter called name. If provided, the function prints a personalized greeting, and if not, it prints Hello, stranger."

Default Parameters

TypeScript also allows you to define default values for parameters. If a value is not provided, the parameter will take the default value.

Example of Default Parameters

typescript
"Here, the greet function has a parameter name with the default value stranger. If no value is passed, the function will use this value, and if a value is passed, it will use the provided one."

Anonymous and Arrow Functions

TypeScript supports anonymous functions and arrow functions, which are a more concise way to write functions. Typing can also be applied to these functions.

Example of Arrow Function

typescript
"In this example, the arrow function multiply takes two parameters, x and y, both of type number, and returns their product."

Conclusion

In this chapter, we have explored how to use functions in TypeScript, from defining types for parameters and return values to using optional and default parameters. Additionally, we saw how to work with arrow functions, which are a concise and modern way to write functions.


Ask me anything