An interfaces specifies a list of fields and functions that may be expected on any class implementing the interface. Conversely, a class cannot implement an interface unless it has every field and function specified on the interface.
The primary benefit of using interfaces, is that it allows one to use objects of different types in a polymorphic way. This is because any class implementing the interface has at least those fields and functions.
Interfaces are good for specifying the shape of an object, eg for a person object you could specify
interface person {
id?: number;
name: string;
age: number;
}
However what if you want to represent, say, the way a person is stored in an SQL database? Seeing as each DB entry consists of a row of shape [string, string, number]
(so an array of strings or numbers), there is no way you could represent this as an object shape, because the row doesn't have any properties as such, it's just an array.
This is an occasion where types come in useful. Instead of specifying in every function that accepts a row parameter function processRow(row: [string, string, number])
, you can create a separate type alias for a row and then use that in every function:
type Row = [string, string, number];
function processRow(row: Row)
https://www.typescriptlang.org/docs/handbook/interfaces.html