Variables are not the only elements that can be restricted and protected with type safety. Functions can also be restricted by type safety to ensure the right data types are passed as arguments and returned when the function is executed.
This happens by dictating the function parameters and its return results.
| Feature | Description | Example |
|---|---|---|
| Parameter Types | Define the type for function parameters. | function greet(name: string) {} |
| Return Type Annotation | Specify the type of the returned value. | function add(a: number, b: number): number { return a + b; } |
void Return Type | Used when a function does not return a value — for example, functions that log to the console or update the DOM. | function logMessage(msg: string): void { console.log(msg); } |
Optional Parameters (?) | Parameters that are not required when calling the function. | function welcome(name: string, age?: number) {} |
| Default Parameters | Assigns a default value if no argument is provided. | function format(price: number, currency: string = "USD") {} |
| Function Expressions | Assign functions to variables. | const multiply = function (x: number, y: number): number { return x * y; }; |
| Arrow Functions | A shorter syntax for functions. | const divide = (a: number, b: number): number => a / b; |
| Function Type Aliases | Define a function structure as a type. | type MathOp = (x: number, y: number) => number; |