Chapter 7. Interfaces
Why only use the
Boring built-in type shapes when
We can make our own!
I mentioned back in Chapter 4, “Objects” that although type aliases for { ... }
object types are a way to describe object shapes, TypeScript also includes an “interface” feature many developers prefer.
Interfaces are another way to declare an object shape with an associated name.
Interfaces are in many ways similar to aliased object types but are generally preferred for their more readable error messages, speedier compiler performance, and better interoperability with classes.
Type Aliases Versus Interfaces
Here is a quick recap of the syntax for how an aliased object type would describe an object with a born: number
and name: string
:
type
Poet
=
{
born
:
number
;
name
:
string
;
};
Here is the equivalent syntax for an interface:
interface
Poet
{
born
:
number
;
name
:
string
;
}
The two syntaxes are almost identical.
Tip
TypeScript developers who prefer semicolons generally put them after type aliases and not after interfaces.
This preference mirrors the difference between declaring a variable with a ;
versus declaring a class or function without.
TypeScript’s assignability checking and error messages for interfaces also work and look just about the same as they do for object types.
The following assignability errors for assigning to the valueLater
variable would be roughly the same if Poet
was an interface or type alias:
let
valueLater
:
Poet
;
// Ok
valueLater
=
{
born
:
1935
,
name
:
'Sara Teasdale' ...
Get Learning TypeScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.