Summary - Type alias
- TypeScript course
- Beginner
- Lesson 58/89
- 4 min
Write a configuration type with aliases.
Summary - Type alias
Type aliases provide reuse by naming types, create new types with unions, and are more general than interfaces. Together they enable flexible and modular type definitions.
type Deger = number | string;
type Ayar = { ad: string; deger: Deger };These features together create powerful configuration types.
Practice Write a configuration type
Define a type alias named Deger (number | string union). Define a type alias named Ayar ({ ad: string; deger: Deger }). Declare a variable named ayar of type Ayar with value { ad: "timeout", deger: 30 }. Print the value of ayar.ad with console.log.
Starter code
// Deger adında bir type alias tanımla (number | string birleşimi)
// Ayar adında bir type alias tanımla ({ ad: string; deger: Deger })
// ayar değişkenini Ayar türünde tanımla, değer: { ad: "timeout", deger: 30 }
// ayar.ad değerini yazdırSample solution
type Deger = number | string;
type Ayar = { ad: string; deger: Deger };
let ayar: Ayar = { ad: "timeout", deger: 30 };
console.log(ayar.ad);Expected output
timeout
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does using another alias in an alias definition enable?
- Building complex types from simple ones Correct answer
- Faster execution
- Less memory usage
- Types becoming immutable
Explanation: Aliases can reference other aliases; this enables building complex types modularly from simpler parts.
2 Complete the configuration value type
type Ayar = {
ad: string;
deger: ____;
};
type Ayar = {
ad: string;
deger: number | string;
};
Explanation: Since a configuration value can be both a number and a string, the type must be <code>number | string</code>; only <code>number</code> or <code>string</code> excludes the other type, and <code>boolean</code> is the wrong type.
3 Type alias summary
| Term | Meaning |
|---|---|
type ID = number |
Primitive type naming |
type X = A | B |
Type union |
type vs interface |
Type is more general |
Type alias |
Naming a type |