CodeBlanks Logo Icon CodeBlanks

Composition with alias

Learn to create new types by combining aliases.

Composition with aliases

You can combine types with | (union) to create a new alias. This is useful when a value can be one of several types. Aliases can also reference other aliases.

type ID = number | string;
type Durum = "acik" | "kapali";

A union type allows a value to be one of several types.

Deriving aliases from aliases

An alias can use another alias in its definition. This lets you build complex types from simpler ones, making code modular.

type ID = number;
type Etiket = string;
type Kayit = ID | Etiket;

You can create hierarchical type definitions by combining aliases.

Practice Compose aliases

Define a type alias named ID (number). Define a type alias named Etiket (string). Define a type alias named Kayit (ID | Etiket union). Declare a variable named kayit of type Kayit with value 42. Print the value of kayit with console.log.

Starter code

index.ts
// ID adında bir type alias tanımla (number)
// Etiket adında bir type alias tanımla (string)
// Kayit adında bir type alias tanımla (ID | Etiket birleşimi)
// kayit değişkenini Kayit türünde tanımla, değeri 42
// kayit değerini yazdır

Sample solution

index.ts
type ID = number;
type Etiket = string;
type Kayit = ID | Etiket;
let kayit: Kayit = 42;
console.log(kayit);

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What kind of type does <code>type Sonuc = number | string</code> create?

  • A type that is only number
  • A type that can be either number or string Correct answer
  • A type that is only string
  • A type that is both number and string simultaneously

Explanation: The <code>|</code> operator creates a union type; the value can be either number or string, not both at the same time.

2 Add the second part of the union type

Question
type Durum = "acik" | ____;
Answer
type Durum = "acik" | "kapali";

Explanation: The Durum type should consist of two values: <code>"acik"</code> and <code>"kapali"</code>; the second value is <code>"kapali"</code>. <code>"acik"</code> is a duplicate, and <code>"bekle"</code> and <code>"aktif"</code> are wrong status values.

3 Composition concepts

Term Meaning
type X = A | B Union type
type X = A (A bir alias) Deriving alias from alias
| Type union operator
Composition Combining aliases

All lessons in Beginner