- Home
- Typescript
- Function Types
Funtion Types
One of the cool things about JavaScript is that you can treat functions like variables, assigning them and passing them around.
let displayMessage = console.log; // No parentheses here
displayMessage('Hello, World!'); // Output: Hello, World!
Now, TypeScript enhances this by allowing us to control exactly what kind of functions can be assigned to a variable. You can define a function type to specify both the types of parameters the function should accept and the type it should return.
Here's a basic example where we define a type for a function that accepts two strings and returns a number:
type TwoStringsToNumber = (first: string, second: string) => number;
In this case, the type TwoStringsToNumber
refers to any function that accepts two string parameters and returns a number. Notice that we only define the function signature (the types), not the function body.
Let's assign this type to a couple of different functions:
let calculateLength: TwoStringsToNumber;
calculateLength = function (firstName: string, lastName: string): number {
return firstName.length + lastName.length;
};
calculateLength = function (x: string, y: string): number {
return x.length - y.length;
};
Both functions are valid since they adhere to the type: they accept two strings and return a number. The parameter names don't need to match, as long as the types are correct.
Syntax Reminder: Don't Skip Parentheses or Names
When defining function types in TypeScript, remember to include both the parentheses and the parameter names. If you skip either, your code won't work correctly:
type InvalidFunctionType = (string) => number; // Incorrect syntax
type InvalidFunctionType2 = arg: string => number; // Also incorrect
Function Types and Callbacks
Function types are particularly handy when dealing with callback functions, which are used frequently in asynchronous code or higher-order functions. By explicitly defining the types for callback functions, you ensure that the right types are passed and returned in your code, making it safer and easier to maintain.