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:
typePoet={born:number;name:string;};
Here is the equivalent syntax for an interface:
interfacePoet{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:
letvalueLater:Poet;// OkvalueLater={born:1935,name:'Sara Teasdale' ...