Functions
TS Function Types
Using Function Types
TypeScript function types define signatures ensuring type safety.
Introduction to Function Types
In TypeScript, function types are a way to describe the types of functions, ensuring that the functions adhere to specific parameter and return type signatures. By defining function types, TypeScript allows you to catch errors during development, making your code more robust and reliable.
Basic Function Type Syntax
A function type in TypeScript can be defined using a parameter list and a return type. The syntax resembles that of an arrow function. Here's a basic example:
In this example, GreetFunction
is a type that describes a function taking a single parameter of type string
and returning a string
.
Implementing Function Types
Once a function type is defined, you can use it to type-check functions. This ensures the function matches the expected signature:
Here, the greet
function is typed using GreetFunction
. This means it must accept a string parameter and return a string, matching the defined signature.
Function Types with Multiple Parameters
Function types can also handle multiple parameters. Simply list each parameter and its type in the function type definition:
This AddFunction
type describes a function that takes two numbers as arguments and returns a number.
The add
function is now validated against AddFunction
, ensuring it accepts two numbers and returns a number.
Optional Parameters in Function Types
TypeScript function types also support optional parameters. Use a question mark (?
) after the parameter name to indicate it's optional:
In this example, userId
is an optional parameter. The function can be called with one or two arguments.
The log
function adheres to LogFunction
, allowing flexibility with the optional userId
parameter.
Conclusion
TypeScript function types offer a powerful way to enforce type safety by defining precise function signatures. This ensures that functions adhere to expected parameter and return types, reducing runtime errors and improving code quality.
Functions
- Previous
- Functions
- Next
- Arrow Functions