Interfaces
8 min · TypeScript
Describe object shapes with interfaces — typed keys instead of numbered positions.
Enemy 1 of 5
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.
Loading editor...