An interface is a way of defining an object type. An “object type” can be thought of as, “an instance of a class could conceivably look like this”.
For example, string | number
is not an object type, because it makes use of the union type operator.
EXTENDS
If you’ve ever seen a JavaScript class that “inherits” behavior from a base class, you’ve seen an example of what TypeScript calls a heritage clause: extends
class Animal { eat(food) { consumeFood(food) } } class Dog extends Animal { bark() { return "woof" } } const d = new Dog() d.eat d.bark
extends
from a base class.extends
from a base interface, as shown in the example belowIMPLEMENTS
TypeScript adds a second heritage clause that can be used to state that a given class should produce instances that confirm to a given interface: implements
.
interface AnimalLike { eat(food): void } class Dog implements AnimalLike { // Error: Class 'Dog' incorrectly implements interface 'AnimalLike'. // Property 'eat' is missing in type 'Dog' but required in type 'AnimalLike'. bark() { return "woof" } }
TypeScript interfaces are “open”, meaning that unlike in type aliases, you can have multiple declarations in the same scope:
You may be asking yourself: where and how is this useful?
Imagine a situation where you want to add a global property to the window
object
window.document // an existing property window.exampleProperty = 42 // tells TS that `exampleProperty` exists interface Window { exampleProperty: number }
What we have done here is augment an existing Window
interface that TypeScript has set up for us behind the scene.
In many situations, either a type
alias or an interface
would be perfectly fine, however…
|
union type operator), you must use a type aliasimplements
heritage term, it’s best to use an interface