interface
A named description of an object’s shape that you can extend and merge.
Example
#interface Course {
id: number
title: string
modules: number
describe(): string
}
const html: Course = {
id: 1,
title: 'HTML and CSS',
modules: 11,
describe() {
return `${this.title}: ${this.modules} modules`
}
}
console.log(html.describe())HTML and CSS: 11 modules
Definition and usage
#An interface gives a name to the shape of an object: it lists its fields and methods along with their types. An object matches the interface if it has the required properties with matching types. It doesn’t need to be created with any special syntax.
You can extend interfaces with the extends keyword, building more specific types out of general ones. Classes can implement them with implements, which guarantees they have the required methods.
A special feature of interfaces is declaration merging: two interfaces with the same name merge into one. That’s how libraries let you extend their types from the outside, for example adding fields to the Window object.
Syntax
#interface Name {
field: type
method(param: type): type
}More examples
#interface Settings {
theme: 'dark' | 'light'
}
interface Settings {
sounds: boolean
}
const settings: Settings = { theme: 'dark', sounds: true }
console.log(Object.keys(settings))['theme', 'sounds']
Good practices
#- For describing objects and class contracts,
interfaceis the natural choice. For unions, tuples, and complex types, usetype. - Name interfaces after what the object is (
User,Course), without anIprefix.
Related entries
#- interface vs typeinterface describes an object’s shape and can be extended or merged with another declaration of the same name, while type aliases any type, including unions and tuples.
- typeA type alias: a name for any type, including unions, tuples, and complex types.
- extends (interfaces)Extending an interface with new fields, based on an existing one.
- implementsA declaration that a class fulfills the contract described by an interface.
- Optional properties (?)Properties that may, but don’t have to, show up in an object.
Spotted a mistake or missing an example? Write to us.