TypeScript interface
A TypeScript interface names the shape of an object, listing each property it has and the type of value it holds. Code that reads an object described by an interface can be checked before it runs, so a misspelt property or a missing field is caught early.
An object in JavaScript can hold any properties at all, which is flexible and also the cause of a common bug: reading a property that is not there, or is spelt differently, and getting undefined. TypeScript lets you describe what an object is expected to hold, and an interface is the usual way to write that description.
What one looks like
An interface lists properties and their types. A user might have an id that is a number, a name that is a string, and an email that is a string or null. A property followed by a question mark is optional. A property holding a list is written with square brackets, and one holding another object refers to that object’s own interface.
Where the shape comes from
For data that arrives from an API, the shape is whatever the API sends, and writing the interface by hand means reading a long response field by field. Generating it from a sample is faster: each value in the sample gives a type, objects inside lists are merged so that a field present in only some of them becomes optional, and a field that is sometimes null keeps null in its type.
What it does not do
An interface is checked when the code is compiled and then removed. It does not stop wrong data arriving at runtime. If the API changes, the interface describes the old shape until it is updated, which is why types written from a sample are worth checking against a larger one.
Frequently asked questions
What is the difference between an interface and a type alias?
For describing an object they do the same job. An interface can be extended and merged with another declaration of the same name, and a type alias can also name unions and other types. Many code bases pick one by convention.
What does a question mark after a property mean?
That the property is optional. The object may have it or not, and code that reads it has to allow for it being missing.
Does an interface check data at runtime?
No. It is checked when the code is compiled and then removed. Data arriving from an API at runtime is not checked against it unless separate validation does that.