Lompati ke konten utama
eLearner.app
Modul 3 · Pelajaran 1 dari 25/14 dalam kursus~12 min
Pelajaran modul (1/2)

Fungsi yang Diketik

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

Latihan#ts.m3.l1.e1
Upaya: 0Memuat…

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

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Exercise 2: Default Parameters

Latihan#ts.m3.l1.e2
Upaya: 0Memuat…

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

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Exercise 3: Function Signature

Latihan#ts.m3.l1.e3
Upaya: 0Memuat…

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.

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Exercise 4: Callback Function

Latihan#ts.m3.l1.e4
Upaya: 0Memuat…

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.

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya