Salt la conținutul principal
eLearner.app
Modulul 3 · Lecția 1 din 25/14 în curs~12 min
Lecții din modul (1/2)

Funcții tipizate

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

Exercițiu#ts.m3.l1.e1
Încercări: 0Se încarcă…

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

Se încarcă editorul...
Afișează indiciu

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

Soluție disponibilă după 3 încercări

Exercise 2: Default Parameters

Exercițiu#ts.m3.l1.e2
Încercări: 0Se încarcă…

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

Se încarcă editorul...
Afișează indiciu

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

Soluție disponibilă după 3 încercări

Exercise 3: Function Signature

Exercițiu#ts.m3.l1.e3
Încercări: 0Se încarcă…

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.

Se încarcă editorul...
Afișează indiciu

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

Soluție disponibilă după 3 încercări

Exercise 4: Callback Function

Exercițiu#ts.m3.l1.e4
Încercări: 0Se încarcă…

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.

Se încarcă editorul...
Afișează indiciu

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

Soluție disponibilă după 3 încercări