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

bookUnion Types and Optional Properties

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

In real applications, data is not always fixed. Sometimes a value can have more than one type, or certain fields may not always be present.

TypeScript allows you to handle these cases using union types and optional properties.

Union Types

A union type allows a variable to hold more than one type:

let id: string | number;

id = 10;
id = "abc123";

This is useful when a value can come in different formats.

Optional Properties

Sometimes an object may have properties that are not always required.

You can mark them as optional using ?:

type User = {
  name: string;
  age?: number;
};

Now the age property can be included or omitted:

let user1: User = { name: "Alice", age: 30 };
let user2: User = { name: "Bob" };

Combining Both

You can use union types and optional properties together:

type Order = {
  id: number | string;
  status?: string;
};
question mark

Which of the following TypeScript property declarations makes the age property optional in an object type?

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

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

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

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

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

Запитати АІ

expand

Запитати АІ

ChatGPT

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

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