Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Working with Functions in TypeScript | Section
TypeScript for Backend Development

bookWorking with Functions in TypeScript

Свайпніть щоб показати меню

In TypeScript, you can define the types of function parameters and return values. This makes your functions more predictable and easier to use correctly.

Typing Function Parameters

You can specify the type of each parameter:

function greet(name: string) {
  return "Hello, " + name;
}

If you pass a value that is not a string, TypeScript will show an error.

Typing Return Values

You can also define what type a function should return:

function add(a: number, b: number): number {
  return a + b;
}

This ensures the function always returns the expected type.

Optional Parameters

Sometimes a parameter is not required. You can mark it as optional using ?:

function greetUser(name: string, age?: number) {
  if (age) {
    return `Hello ${name}, you are ${age}`;
  }
  return `Hello ${name}`;
}

Arrow Functions

You can also use arrow functions with types:

const multiply = (a: number, b: number): number => {
  return a * b;
};
question mark

What can you explicitly type in a TypeScript function to make your code more predictable and type safe?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 4
some-alt