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.create('myMethodA', 'myMethodB')
or alternatively
const MyInterface = new Interface('myMethodA', 'myMethodB')
Next, just make your class extend from the interface. Make sure you call super()
within your class's constructor.
class MyClass extends MyInterface {
constructor () {
super()
}
myMethodA () {
}
}
Now, whenever you try to instantiate MyClass
, the interface will be enforced.
let instance = new MyClass()
Of course, the interface is enforced on all subclasses as well.
class MySubClass extends MyClass {
constructor () {
super()
}
myMethodA () {
}
}
let instance = new MySubClass()
Interfaces can be enforced for classes defined the old way too.
const inherits = require('util').inherits
var MyInterface = new Interface('myMethodA', 'myMethodB', 'myMethodC')
function MyClass () {
MyInterface.call(this)
}
inherits(MyClass, MyInterface)
MyClass.prototype.myMethodA = function () {
}
function MySubClass () {
MyClass.call(this)
}
inherits(MySubClass, MyClass)
MySubClass.prototype.myMethodB = function () {
}
var instance = new MySubClass()