Skip to Content
Learning TypeScript
book

Learning TypeScript

by Josh Goldberg
June 2022
Beginner
320 pages
6h 40m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning TypeScript

Chapter 7. Interfaces

Why only use the

Boring built-in type shapes when

We can make our own!

I mentioned back in Chapter 4, “Objects” that although type aliases for { ... } object types are a way to describe object shapes, TypeScript also includes an “interface” feature many developers prefer. Interfaces are another way to declare an object shape with an associated name. Interfaces are in many ways similar to aliased object types but are generally preferred for their more readable error messages, speedier compiler performance, and better interoperability with classes.

Type Aliases Versus Interfaces

Here is a quick recap of the syntax for how an aliased object type would describe an object with a born: number and name: string:

type Poet = {
  born: number;
  name: string;
};

Here is the equivalent syntax for an interface:

interface Poet {
  born: number;
  name: string;
}

The two syntaxes are almost identical.

Tip

TypeScript developers who prefer semicolons generally put them after type aliases and not after interfaces. This preference mirrors the difference between declaring a variable with a ; versus declaring a class or function without.

TypeScript’s assignability checking and error messages for interfaces also work and look just about the same as they do for object types. The following assignability errors for assigning to the valueLater variable would be roughly the same if Poet was an interface or type alias:

let valueLater: Poet;

// Ok
valueLater = {
  born: 1935,
  name: 'Sara Teasdale' ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Understanding TypeScript

Understanding TypeScript

Maximilian Schwarzmüller

Publisher Resources

ISBN: 9781098110321Errata PageSupplemental Content