how to implement an interface in javascript as natively as possible?


objects are created in the program like this:

var obj;

these objects are passed to functions:

function print(o){
  console.log( o.a +' '+o.b );

The problem is that when the same objects are created and used in different places, it is very difficult to manually monitor the properties, but in Java this is done automatically and if something goes wrong, an error is generated.

I would like to have an interface like in Java. maybe something like this:

function Data(){
var obj = new Data();

just to check for a type match or a match of the object's property list with the type …

I know about TypeScript, and there are still a bunch of bicycles / libraries … but I would like to know how this is usually implemented in JavaScript? normal?

maybe in ES5 or ES6?


You can always implement something like this yourself:

Function.prototype.hint = function(...types) {
  let fn = this;
  return function(...args) {
    if (args.length !== types.length) throw new Error('Wrong arg num');
    types.forEach((type, i) => {
      if (!(args[i] instanceof type)) throw new Error('Wrong arg type');
    return fn(...args);


class IFoo {
  constructor(foo){ = foo;}
  getFoo() {return;}

class A extends IFoo {}
class B {}

const hintedFoo = (function(Foo) {
}).hint(IFoo); // Typehinting

hintedFoo(new A('success'));
hintedFoo(new B('fail'));
Scroll to Top