Command Palette

Search for a command to run...

Hectal
Phase 3Beginner4 of 18 in TypeScript

Type Aliases and Interfaces

Name your own types with type and interface, extend and combine shapes, understand structural typing, and model dictionaries with index signatures and Record.

Until now you used the types that come with the language: string, number, arrays and plain objects. Real programs have their own ideas: a user, a point on a map, an order. This phase teaches the two tools TypeScript gives you to give those ideas a name: type aliases and interface declarations.

You'll learn how to describe object shapes with optional and read-only members, how to build big shapes out of small ones with extends and &, and when to choose type or interface. Then comes the idea that explains most of TypeScript's behaviour, structural typing: the checker compares what a value looks like, not what it is called.

The phase ends with index signatures and Record, the tools for dictionaries where you don't know the keys in advance, including a real runtime trap ("constructor" as a key) that the checker cannot see.

0/6 · 0%
6 topics ~2 h 21 code blocks & diagrams
Start with the first topic
1
3.1

Type Aliases

A type alias gives a name to any type with type Name = ..., so you can write a long or important type once and reuse it. The name is only a label: it does not create a new, different type.

22 min 3 code practice

2
3.2

Interfaces

An interface describes the shape of an object: which properties it has, which are optional, which cannot be changed, and which methods it offers. It is a contract that any object can be checked against.

21 min 3 code practice

3
3.3

Extending and Combining Shapes

Build big shapes out of small ones: an interface can extend one or more others, and the & operator glues any types into an intersection. When the pieces disagree about a property, the result can quietly become never.

22 min 3 code practice

4
3.4

type or interface?

For plain object shapes type and interface do almost the same job. This topic covers the real differences: interfaces merge, aliases can name any type, and the two behave a little differently in errors and speed. It ends with a simple team rule.

22 min 4 code practice

5
3.5

Structural Typing

TypeScript decides whether a value fits a type by looking at its shape, the members it has, and not at the name of its class or interface. This one idea explains why code that "shouldn't" compile does, and why some obvious-looking errors appear.

23 min 4 code practice

6
3.6

Index Signatures and Records

When an object is a dictionary, with keys you don't know in advance, you describe it with an index signature [key: string]: T or the shorthand Record<K, V>. Reading a missing key gives undefined, and a safer tool, Map, exists for when keys are arbitrary.

21 min 4 code practice

Practise this phase

Hands-on exercises: write the code, see your page live, and press Check to have it tested automatically.