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

Question:

objects are created in the program like this:

var obj;
obj.a=123;
obj.b='abc';

these objects are passed to functions:

print(obj);
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(){
   this.a=0;
   ths.b='';
}
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?

Answer:

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){ this.foo = foo;}
  getFoo() {return this.foo;}
}

class A extends IFoo {}
class B {}


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

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