Search code examples
javascriptadt

Is javascript support abstract data type?


Is javascript support abstract data type ?

I search lot but i did not find any answer. I think it does not support is it correct?


Solution

  • No, but you can simulate it (in ES2015+) by using new.target:

    class Abstract {
      constructor(value) {
        if (new.target === Abstract) {
          throw new Error("Abstract is abstract");
        }
        this.value = value; // Proof that if the check above is false,
                            // we *do* continue to set up the instance
      }
    }
    class Concrete extends Abstract {
    }
    try {
      const a = new Abstract(1);
      console.log("Got Abstract instance, value = " + a.value);
    } catch (e1) {
      console.error(e1);
    }
    try {
      const c = new Concrete(2);
      console.log("Got Concrete instance, value = " + c.value);
    } catch (e2) {
      console.error(e2);
    }

    Sadly, this only produces an error when the line of code trying to do the instantiation runs, not when it's parsed/compiled.

    TypeScript, which is a derivative of JavaScript that adds type checking and a few other things, has the concept of abstract classes, which are flagged up during the TypeScript compilation stage (when the TypeScript is compiled [or "transpiled"] to JavaScript); the information is also available to IDEs and such for instant feedback.