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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With