Skip to main content
eLearner.app
Module 3 · Lesson 1 of 25/14 in the course~12 min
Module lessons (1/2)

Typed Functions

Functions are the fundamental building blocks of any JavaScript application. In TypeScript, we can precisely annotate both input arguments and return values, making our interfaces and function calls extremely safe and self-documenting.


Optional and Default Parameters

In JavaScript, every parameter is optional and defaults to undefined if omitted. In TypeScript, by default, every declared parameter is mandatory.

However, we can define optional parameters using the question mark (?), or specify default values directly in the function signature.

1. Optional Parameters

Optional parameters must be positioned after all mandatory parameters:

TS
function greetUser(name: string, title?: string): string {
  if (title) {
    return `Good morning ${title} ${name}`;
  }
  return `Hello ${name}`;
}

2. Default Parameters

If no value is provided for a parameter with a default value, TypeScript infers its type and assigns the specified default:

TS
function greetUserWithDefault(name: string, prefix: string = 'Hello'): string {
  return `${prefix} ${name}`;
}

Rest Parameters (...args)

When we want to accept a variable number of arguments, we can use the rest operator. In TypeScript, these parameters must be typed as an array:

TS
function sumAll(message: string, ...numbers: number[]): string {
  const total = numbers.reduce((sum, n) => sum + n, 0);
  return `${message} ${total}`;
}

Function Types (Call Signatures)

We can define a function's type independently and then reuse it in variable declarations or callback arguments:

TS
// Define function type using type alias
type MathOperation = (a: number, b: number) => number;

const add: MathOperation = (x, y) => x + y;
const multiply: MathOperation = (x, y) => x * y;

This approach is essential when passing functions as arguments to other functions (callbacks).


Try it yourself

Exercise 1: Optional Parameters

Exercise#ts.m3.l1.e1
Attempts: 0Loading…

Create a function named formatName that accepts a firstName parameter (string) and an optional lastName parameter (string). If lastName is provided, return 'firstName lastName', otherwise return only 'firstName'.

Loading editor…
Show hint

Remember that the optional parameter is declared using lastName?: string after the mandatory one.

Solution available after 3 attempts

Exercise 2: Default Parameters

Exercise#ts.m3.l1.e2
Attempts: 0Loading…

Create a function named power that accepts a base (number) and an exponent (number with a default value of 2). The function must calculate and return the value of base raised to the exponent (use Math.pow).

Loading editor…
Show hint

Use base: number and exponent: number = 2 within the function signature.

Solution available after 3 attempts

Exercise 3: Function Signature

Exercise#ts.m3.l1.e3
Attempts: 0Loading…

Define a type alias named BinaryOp that describes a function accepting two number parameters and returning a number. Next, declare a constant named sum of type BinaryOp that implements addition.

Loading editor…
Show hint

The syntax for a function type is (a: number, b: number) => number.

Solution available after 3 attempts

Exercise 4: Callback Function

Exercise#ts.m3.l1.e4
Attempts: 0Loading…

Create a function named processItems that accepts two parameters: items (an array of strings) and callback (a function that accepts a single string and returns nothing, i.e., void). The function must run a for...of loop over each element in items and pass it to the callback.

Loading editor…
Show hint

Declare the signature as processItems(items: string[], callback: (item: string) => void): void and use a loop to call the callback.

Solution available after 3 attempts