Перейти до основного вмісту
eLearner.app
Модуль 3 · Урок 1 із 25/14 у курсі~12 min
Модульні уроки (1/2)

Типізовані функції

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

вправи#ts.m3.l1.e1
Спроби: 0Завантаження…

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'.

Завантаження редактора…
Показати підказку

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

Рішення доступне після 3 спроб

Exercise 2: Default Parameters

вправи#ts.m3.l1.e2
Спроби: 0Завантаження…

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).

Завантаження редактора…
Показати підказку

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

Рішення доступне після 3 спроб

Exercise 3: Function Signature

вправи#ts.m3.l1.e3
Спроби: 0Завантаження…

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.

Завантаження редактора…
Показати підказку

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

Рішення доступне після 3 спроб

Exercise 4: Callback Function

вправи#ts.m3.l1.e4
Спроби: 0Завантаження…

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.

Завантаження редактора…
Показати підказку

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

Рішення доступне після 3 спроб