Interfaces
8 min · TypeScript
Describe object shapes with interfaces: typed keys instead of numbered positions.
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.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.