TypeScript Functions

Functions are the fundamental building blocks of any application. In TypeScript, they take the flexibility of JavaScript and add a layer of "contractual" safety. By defining types for your inputs (parameters) and outputs (return values), you catch bugs during development rather than at runtime. This turns your functions into self-documenting code that tells other developers exactly what to expect.

Best Practice: Always explicitly define the return type of your functions. While TypeScript is great at guessing (inferring) the return type, explicitly declaring it ensures you don't accidentally return the wrong data type as your function logic grows.

 

Syntax for Functions

Basic Syntax:

A TypeScript function looks very similar to JavaScript, but with type annotations added after the parameters and before the curly braces.

function functionName(param1: type, param2: type): returnType {  
  // function body  
  return value;
}  
Developer Tip: Think of the function signature as a contract. If you promise to return a string, TypeScript will highlight an error if you try to return a number.

 

Function Types

Functions with Parameter Types and Return Types

  • Adding types prevents common "undefined" errors. For example, if a function expects a number and you pass a string, the compiler will stop you immediately.
Common Mistake: Forgetting that by default, all parameters defined in a function are required. If you define three parameters, you must pass three arguments.

Optional Parameters

  • In some cases, a function doesn't need every piece of data to run. You can make a parameter optional by adding a ? after its name. Important: Optional parameters must always appear after any required parameters.
function greet(name: string, greeting?: string): string {
  return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`;
}

Default Parameters

  • If you want a parameter to have a fallback value when nothing is provided, use default parameters. This also makes the parameter optional for the caller.
Watch Out: You cannot mark a parameter as both optional (?) and give it a default value. The default value already implies that the parameter is optional.

Rest Parameters

  • When you don't know how many arguments a user will pass (like summing a list of numbers), use rest parameters. The ... syntax collects multiple arguments into a single array.
function sumAll(...numbers: number[]): number {
  return numbers.reduce((total, num) => total + num, 0);
}

Anonymous Functions

Anonymous functions (functions without a name) are often used when passing a function as an argument to another function, or when assigning a function to a constant.

const multiply = function (a: number, b: number): number {  
  return a * b;  
};  

console.log(multiply(5, 3)); // Output: 15  

Arrow Functions

Arrow functions are the modern standard in React and Node.js development. They provide a shorter syntax and handle the this keyword more predictably in classes.

const subtract = (a: number, b: number): number => a - b;  

console.log(subtract(10, 3)); // Output: 7  
Developer Tip: Use arrow functions for short, one-liner logic or when working with array methods like .map() or .filter().

Function Overloading

Sometimes a single function needs to handle different types of inputs and return different types of results based on those inputs. Function overloading allows you to define multiple "shapes" for the same function.

// Overload signatures
function combine(a: string, b: string): string;  
function combine(a: number, b: number): number;  

// Actual implementation
function combine(a: any, b: any): any {  
  return a + b;  
}  

console.log(combine(5, 10));         // Output: 15  
console.log(combine("Hello, ", "World!")); // Output: Hello, World!  
Common Mistake: The implementation signature (the one with the actual code) is not callable directly. Only the overload signatures are visible to the code using the function.

Void Return Type

If a function performs an action (like logging to a console or saving to a database) but doesn't send a value back to the caller, use void.

function logMessage(message: string): void {  
  console.log(message);  
}  

logMessage("Hello, TypeScript!"); // Output: Hello, TypeScript!  

Never Return Type

The never type is rare but powerful. It represents a function that never finishes successfully. This happens if the function always throws an error or enters an infinite loop.

function handleCriticalError(message: string): never {  
  throw new Error(message);  
}  

Example: Function with Multiple Features

In real-world projects, you’ll often mix these concepts. Here is a function that uses a required parameter, an optional parameter, and rest parameters together.

function displayInfo(name: string, age?: number, ...hobbies: string[]): string {  
  const ageInfo = age ? `, Age: ${age}` : "";  
  const hobbiesInfo = hobbies.length ? `, Hobbies: ${hobbies.join(", ")}` : "";  

  return `Name: ${name}${ageInfo}${hobbiesInfo}`;  
}  

console.log(displayInfo("John"));  
console.log(displayInfo("Alice", 25, "Reading", "Traveling"));  

Output:

Name: John  
Name: Alice, Age: 25, Hobbies: Reading, Traveling  
Best Practice: When using rest parameters, always ensure you type the array correctly (e.g., string[] or number[]) to prevent accidental type mixing inside the function body.

 

Summary

Mastering functions in TypeScript is about more than just syntax—it's about writing code that is predictable and easy to maintain. By utilizing parameter types, optional values, and specific return types like void or never, you create a safety net for your future self and your teammates. Whether you are using traditional declarations or concise arrow functions, TypeScript ensures that your logic remains robust as your application scales.