codez.guru

Function Parameters and Return Types

You can type both parameters and return values:

function add(x: number, y: number): number {
  return x + y;
}

This ensures the function always receives and returns the correct types.


Type Inference in Functions

TypeScript can infer the return type:

function greet(name: string) {
  return `Hello, ${name}`;
}

But for public APIs or exports, it’s best to explicitly define return types for clarity and safety.


Optional and Default Parameters

Optional parameter

function log(message: string, user?: string) {
  console.log(`${message}${user ? " from " + user : ""}`);
}

Default parameter

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

Arrow Functions and Typing

Arrow functions can be typed like this:

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

You can also define the function type separately:

const divide: (a: number, b: number) => number = (a, b) => a / b;

Function Types as Variables

You can define reusable function signatures:

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

const add: MathOperation = (a, b) => a + b;
const sub: MathOperation = (a, b) => a - b;

This is especially helpful for callbacks or utilities passed between components.


Summary

  • Type parameters and return values explicitly for safety and clarity
  • TypeScript can infer return types but prefer annotations for public APIs
  • Use ? for optional parameters and = for default values
  • Arrow functions can also be typed cleanly using type aliases

Up next: how to define objects and interfaces with optional, readonly, and structured properties.