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

Псевдоніми типів проти інтерфейсів

In TypeScript, we can define the structure of complex objects in two primary ways: using Interfaces (interface) or Type Aliases (type). Both serve to describe the "shape" of an object or data structure, but they have a few fundamental differences.


Interfaces (interface)

An interface defines a contract for the structure of an object. It is the standard tool to describe object shapes and public APIs in an extensible way.

TS
interface Book {
  title: string;
  pages: number;
  author?: string; // Optional property (can be omitted)
}

const myBook: Book = {
  title: 'The Lord of the Rings',
  pages: 1200,
};

The question mark (?) marks a property as optional. The myBook object is valid even if it omits the author property.


Type Aliases (type)

A type alias allows you to associate a new name with any existing type, including primitive types, unions, tuples, or entire object structures.

TS
type Point = {
  x: number;
  y: number;
};

const coordinates: Point = { x: 10, y: 20 };

Key Differences: Extension and Declaration Merging

Although interface and type are interchangeable for most ordinary use cases, they exhibit two critical differences:

1. Extensibility (Inheritance)

Interfaces are extended using the extends keyword:

TS
interface User {
  username: string;
}

interface Admin extends User {
  privileges: string[];
}

Type aliases cannot be extended using extends, but they can be combined using the intersection operator (&):

TS
type User = {
  username: string;
};

type Admin = User & {
  privileges: string[];
};

2. Declaration Merging

Multiple interfaces with the same name in the same scope are automatically merged by the compiler:

TS
interface User {
  name: string;
}
interface User {
  email: string;
}
// Now User has both 'name' and 'email'!

This behavior is not supported by type aliases: declaring the same type twice will trigger a compile-time error.


Try it yourself

Exercise 1: User Interface

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

Define an interface named User that describes a user object. The interface must contain: id as a number, username as a string, and email as an optional string.

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

Use the syntax email?: string to mark it as optional.

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

Exercise 2: Point2D Type Alias

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

Create a type alias named Point2D representing a two-dimensional point with coordinates x and y (both numbers).

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

Use the syntax type Point2D = { x: number; y: number; };

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

Exercise 3: Extending Interfaces

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

Define an interface named Product with id (number) and price (number). Next, define an interface named DiscountedProduct that extends Product and adds an optional property named discountCode (string).

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

Use extends Product to inherit the fields, and add discountCode?: string.

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

Exercise 4: Server Configuration

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

Define a type alias named ServerConfig representing a configuration object for a server. It must contain: host (string), port (number), and useHttps as an optional boolean field.

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

Use the syntax type ServerConfig = { host: string; port: number; useHttps?: boolean; }.

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