Skip to main content

TypeScript Functions

Functions are blocks of reusable code that perform specific tasks. TypeScript adds type safety to JavaScript functions, making them more reliable and easier to understand.

Basic Function Types

Here's how to declare function parameters and return types:

function calculateTotal(price: number, quantity: number): number {
return price * quantity;
}

// Using the function
const total = calculateTotal(25, 3); // returns 75

Optional and Default Parameters

You can make parameters optional or provide default values:

function greetUser(name: string, greeting = "Hello"): string {
return `${greeting}, ${name}!`;
}

// Both are valid
greetUser("John"); // "Hello, John!"
greetUser("John", "Hi"); // "Hi, John!"

Function Types

TypeScript allows you to define function types:

type MathOperation = (a: number, b: number) => number;

const add: MathOperation = (a, b) => a + b;
const multiply: MathOperation = (a, b) => a * b;

Arrow Functions

Arrow functions provide a concise syntax and maintain the parent scope's this context:

type User = {
name: string;
age: number;
};

const users: User[] = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 }
];

// Arrow function with implicit return
const getNames = (users: User[]): string[] =>
users.map(user => user.name);

Common Patterns

  1. Function Overloads
function handleInput(value: string): string;
function handleInput(value: number): number;
function handleInput(value: string | number): string | number {
return value;
}
  1. Generic Functions
function firstElement<T>(arr: T[]): T | undefined {
return arr[0];
}

// TypeScript infers the correct return type
const first = firstElement([1, 2, 3]); // number
const name = firstElement(["Tom", "Jerry"]); // string

Best Practices

  1. Always specify parameter and return types
  2. Use type inference when it makes code clearer
  3. Keep functions focused on a single task
  4. Document complex functions with JSDoc comments

Practice Exercise

Create a function that takes an array of numbers and returns both the minimum and maximum values. Use a tuple type for the return value.