Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a class in another file

I have some TypeScript code that is being generated by a tool. I'd like to extend this class in another file. As of 0.9.1.1, what's the best way to go about this?

I thought maybe I could staple my additional functions onto the prototype, but this is giving various errors (which change depending what mood the compiler is in).

For example:

Foo.ts (generated by a tool)

module MyModule {
    export class Dog { }
}

Bar.ts

module MyModule {
    function bark(): string {return 'woof';}

    Dog.prototype.bark = bark;
}
like image 214
MgSam Avatar asked Dec 19 '25 21:12

MgSam


1 Answers

You cannot split a class definition between multiple files in TypeScript. However typescript understands how JavaScript works and will let you write idomatic JavaScript classes just fine:

module MyModule {
     export function Dog(){};
}

module MyModule {
    function bark(): string {return 'woof';}
    Dog.prototype.bark = bark;
}

Try it online

One way around this is to use inheritance:

class BigDog extends Dog{
     bark(){}
}
like image 168
basarat Avatar answered Dec 24 '25 10:12

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!