All lessons

Interfaces

8 min · TypeScript

Describe object shapes with interfaces: typed keys instead of numbered positions.

TypeScript · Interfaces0/5 cleared

Enemy 1 of 5

This code uses an interface to say every Player must have a name and a score, then makes one player and logs its name. Press Run to see it.

Why this works

A plain JavaScript object can hold any keys with any values, and nothing stops two objects meant to represent "the same kind of thing" from ending up with slightly different shapes: one player object missing a score, another with it misspelled. An interface fixes that by naming the exact keys and types an object of a certain shape should have.

Once you write interface Player { name: string; score: number; }, any variable typed as Player is guaranteed by the compiler to have both a name (a string) and a score (a number), no more, no less, unless the interface says an extra field is optional. Values are still looked up the normal way, with dot notation (player.name), exactly like plain JavaScript objects.

This is one of TypeScript's most-used features in real code, because so much of a typical application is passing structured objects (users, products, API responses) between functions, and interfaces make sure every function agrees on what shape those objects are supposed to have.

You
Kernel Hellhound
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.