I advise you not to do this. When the TypeScript compiler implements the abstract function mechanism, it's time to use it. But the hacks that run at runtime are incomprehensible and degrade performance.
Interfaces are the great power of TypeScript. They should be used in bulk.
Your example should be written as follows:
interface Engine { getSize(): number; getTurbo(): boolean; } class StandardEngine implements Engine { constructor(private size: number, private turbo: boolean) { } public getSize(): number { return this.size; } public getTurbo(): boolean { return this.turbo; } }
The simplest solution is often the best.
If you want to reuse code without a parent class, which then will definitely be used, the directory offers Mixins . Mixins are a way to master skills from several different objects.
Or, with the help of modules, you can save a private implementation (and, therefore, organize it at your discretion) and export only interfaces and factories. Example:
module MyEngineModule { export interface Engine { getSize(): number; getTurbo(): boolean; } export interface StandardEngine extends Engine { } export function makeStandardEngine(size: number, turbo: boolean): StandardEngine { return new ImplStandardEngine(size, turbo); }
source share