TypeScript from JavaScript

Lesson 2 of 6

Interfaces and Types

As programs grow, describing the shape of your data becomes just as important as describing its logic. TypeScript gives you two main tools for that: interfaces and type aliases.

TypeScript

Interfaces describe object shapes

interface Course { ... } says: "a Course is an object with exactly these properties." Passing an object missing title, or with a lessons that's a string instead of a number, is a compile error. The ? after published marks it optional, an object can be a valid Course with or without it.

Union types restrict the possible values

type Role = 'STUDENT' | 'INSTRUCTOR' | 'ADMIN'; means a Role can only ever be one of those three exact strings, nothing else. Try passing 'ADMINISTRATOR' where a Role is expected, and the compiler catches the typo immediately, something plain JavaScript could never do.

NOTE

interface and type overlap a lot in practice, a common convention is: use interface for the shape of objects, and type for unions, primitives, or anything an interface can't express.

📝 Types Quiz

Passing score: 70%
  1. 1.What does the ? in `published?: boolean` mean?

  2. 2.Which symbol combines types into a union?