
Ts Functions in TypeScript
Functions in TypeScript extend the functionality of JavaScript functions by adding type safety. You can define the types of input parameters, return values, and even use advanced features like default parameters, optional parameters, and function overloading.
Basic Function Syntax
You can explicitly define the types of parameters and return values in a function.
Example: Basic Typed Function
function logMessage(message: string): function displayInfo(name: string, age?: number): console.log(displayInfo("Bob", 25)); // "Bob is 25 years old."
Default Parameters
Default values can be provided for parameters. These are used if no argument is passed or if undefined
is passed.
function calculateArea(length: number, width: number = 10): console.log(calculateArea(5, 20)); // 100
Rest Parameters
Rest parameters allow you to accept an indefinite number of arguments as an array.
function sum(...numbers: number[]): number { return numbers.reduce((acc, num) => acc + num, 0);}console.log(sum(1, 2, 3)); // 6console.log(sum(10, 20, 30, 40)); // 100
Function Overloading
TypeScript allows function overloading, where multiple function signatures can be declared with different parameter types and counts.
Example: Function Overloading
function add(a: number, b: number): console.log(add("Hello, ", "World!")); // "Hello, World!"
Here:
- The first two lines define the function signatures.
- The implementation uses
any
to handle both cases.
Arrow Functions
Arrow functions provide a concise syntax for writing functions. They are especially useful for short, anonymous functions.
Example: Arrow Function
const multiply = (a: number, b: number): number => a * b;console.log(multiply(2, 3)); // 6
Arrow functions also automatically bind this
to the surrounding scope, making them ideal for use in callback functions.
Functions as Types
You can explicitly define the type of a function, including its parameters and return value.
Example: Function Types
type GreetFunction = (name: string) => setTimeout(function (): void { console.log("This runs after 1 second.");}, 1000);
Or using an arrow function:
setTimeout(() => { console.log("This runs after 1 second.");}, 1000);
Callback Functions
You can define the type of a callback function for better type safety.
Example: Callback Function
function processString(input: string, callback: (text: string) => string): string => text.toUpperCase();console.log(processString("hello", upperCase)); // "HELLO"
Generics in Functions
Generic functions allow you to create reusable components that work with various types.
Example: Generic Function
function identity<T>(value: T): T { return value;}console.log(identity(42)); // 42console.log(identity("TypeScript")); // "TypeScript"
Here, T
is a placeholder for the type that the function will operate on.
Asynchronous Functions
TypeScript supports asynchronous functions using the async
keyword, along with Promise
for the return type.
Example: Async Function
async function fetchData(url: string): function square(num: number) { function calculate(a: number, b: number): number { return a + b;}
Use Optional and Default Parameters Appropriately: Use optional parameters for values that are truly optional and default parameters to provide sensible defaults.
Leverage Arrow Functions: For short, inline functions, arrow functions are cleaner and more concise.
Avoid any
When Possible: Instead, use specific types or generics to maintain type safety.
Document Complex Functions: Use comments or JSDoc to explain the purpose and usage of functions.