TypeScriptInterfaces and classes
implements
A declaration that a class fulfills the contract described by an interface.
Example
#TypeScript
interface Scorable {
score(): number
}
class Quiz implements Scorable {
constructor(private correct: number, private total: number) {}
score(): number {
return Math.round((this.correct / this.total) * 100)
}
}
const quiz = new Quiz(8, 10)
console.log(`Score: ${quiz.score()}%`)Result
Score: 80%
Definition and usage
#The implements keyword after a class name tells the compiler that the class must have all the fields and methods from the given interface. If something is missing or the types donât match, an error appears.
This check only concerns types: implements inherits no code at all. The class has to implement every method itself. For inheriting code, use extends between classes.
One class can implement several interfaces, which lets you describe independent capabilities, for example Serializable and Comparable.
Syntax
#Syntax
class Name implements Interface1, Interface2 {
âŠ
}More examples
#TypeScript
class Exam implements Scorable {}
// Error: Class 'Exam' incorrectly implements interface 'Scorable'.
// Property 'score' is missing in type 'Exam' but required in type 'Scorable'.Good practices
#implementsdoesnât change the types inside the class. You still have to type the method parameters in the class itself.- Interfaces that describe capabilities (what an object can do) combine better than deep class inheritance.
Related entries
#- extends vs implementsextends inherits fields and code from a base class, while implements only forces a class to have an interfaceâs methods and fields, without any of its code.
- interfaceA named description of an objectâs shape that you can extend and merge.
- abstract classA base class you canât create directly, with methods for its descendants to fill in.
- public, private, protectedAccess modifiers that control where a classâs fields and methods can be used from.
- extends (interfaces)Extending an interface with new fields, based on an existing one.
Spotted a mistake or missing an example? Write to us.