Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

interface

Package Overview
Dependencies
Maintainers
2
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

interface

Enforce an interface on classes

  • 1.0.0
  • Source
  • npm
  • Socket score

Version published
Maintainers
2
Created
Source

Interface-js

Build Status

Exposes a way to enforce an interface on classes.

Usage

To enforce an interface, first create a new Interface and pass it the function names that you want to enforce.

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 () {
    // ...implementation goes here
  }
}

Now, whenever you try to instantiate MyClass, the interface will be enforced.

let instance = new MyClass()
// 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.

class MySubClass extends MyClass {
  constructor () {
    super()
  }

  myMethodA () {
    // override 'myMethodA'
  }
}

let instance = new MySubClass()
// 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.

var inherits = require('util').inherits

var MyInterface = new Interface('myMethodA', 'myMethodB', 'myMethodC')

function MyClass () {
  MyInterface.call(this)
}

MyClass.prototype.myMethodA = function () {
  // implementation
}

function MySubClass () {
  MyClass.call(this)
}

// inherit prototype of parent class
inherits(MySubClass, MyClass)

MySubClass.prototype.myMethodB = function () {
  // implementation
}

var instance = new MySubClass()
// throws an error with the message:
// 'The following function(s) need to be implemented for class MyClass: myMethodC'

Keywords

FAQs

Package last updated on 24 Feb 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc