Interface-js
Exposes a way to enforce an interface on classes.
Installation
npm install --save interface
Usage
To enforce an interface, first create a new Interface
and pass it the function names that you want to enforce.
const MyInterface = Interface
or alternatively
const MyInterface = 'myMethodA' 'myMethodB'
Next, just make your class extend from the interface. Make sure you call super()
within your class's constructor.
{ super } { // ...implementation goes here }
Now, whenever you try to instantiate MyClass
, the interface will be enforced.
const instance = // throws a new error with the message:// 'The following function(s) need to be implemented for class MyClass: myMethodB'
Of course, the interface is enforced on all subclasses as well.
{ super } { // override 'myMethodA' } const instance = // still throws an error with the message:// 'The following function(s) need to be implemented for class MyClass: myMethodB'
Interfaces can be enforced for classes defined the old way too.
const inherits = inherits const MyInterface = 'myMethodA' 'myMethodB' 'myMethodC' { MyInterface} MyClassprototype { // implementation} { MyClass} // inherit prototype of parent class MySubClassprototype { // implementation} var instance = // throws an error with the message:// 'The following function(s) need to be implemented for class MyClass: myMethodC'
You can also enforce that arbitrary objects match an interface by using
the isImplementedBy
method.
const MyInterface = 'myMethod' { // some implementation } { // some implementation } const instanceA = const instanceB = MyInterface // returns trueMyInterface // returns false