Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I simulate an abstract class and call its constructor?

I'm trying to follow along with a C# design patterns book by writing my code in TypeScript. Perhaps this is my first mistake, but it's a way I enjoy to learn a language.

TypeScript doesn't support the abstract keyword for classes, so I am trying to simulate it. Maybe this is my second mistake.

Here is my interface and classes:

interface IEngine {
  getSize(): number;
  getTurbo(): boolean;
}

class AbstractEngine implements IEngine {
  constructor(private size: number, private turbo: boolean) {
    throw "Abstract class";
  }

  public getSize(): number {
    return this.size;
  }

  public getTurbo(): boolean {
    return this.turbo;
  }

  public toString(): string {
    var funcNameRegex = /function (.{1,})\(/;
    var results = (funcNameRegex).exec(this.constructor.toString());
    var className = (results && results.length > 1) ? results[1] : '';
    return className + " (" + this.size + ")";
  }
}

class StandardEngine extends AbstractEngine {
  constructor(size: number) {
    // not turbo charged
    super(size, false);
  }
}

When trying to instantiate an AbstractEngine with new AbstractEngine(1, true) I get an "Abstract class" error as expected.

When trying to instantiate a StandardEngine with new StandardEngine(9000) I also get an "Abstract class" error.

Is there a way I can simulate an abstract class in TypeScript, have it unable to be instantiated, but still call super in a class that extends it? And what about simulating abstract methods, can I protect those and still call the super method?

like image 897
brycedarling Avatar asked Jul 18 '14 04:07

brycedarling


1 Answers

As of today, TypeScript 1.6 is live and has support for the abstract keyword.

abstract class A {
  foo(): number { return this.bar(); }
  abstract bar(): number;
}

var a = new A();  // error, Cannot create an instance of the abstract class 'A'

class B extends A {
  bar() { return 1; }
}

var b = new b();  // success, all abstracts are defined
like image 192
Fenton Avatar answered Oct 17 '22 04:10

Fenton