Is it possible to declare a class in one file and define its methods in separate files?
I have some classes with a lot of methods and it would be great if I could spread them out a bit.
Short answer: Typescript doesn't support splitting up a class definition into several files.
Workaround: You could define an interface containing members for the class, and two different classes implementing that interface. Then mixin properties from one class to the other, to make a combined class. For example:
LargeClass.a.ts
interface LargeClass {
methodA(): string;
methodB(): string;
}
class LargeA implements LargeClass {
methodA: () => string; // not implemented, needed since otherwise we don't extend LargeClass
methodB() {
return "Hello world";
}
}
LargeClass.b.ts
class LargeB implements LargeClass {
methodA() {
return "Foo";
}
methodB: () => string; // not implemented, needed since otherwise we don't extend LargeClass
}
Usage.ts
// Using underscore's extend to copy implementation from A to B
var c:LargeClass = _.extend(new LargeA(), new LargeB());
// Manually mixing in a to b
var a = new LargeA();
var b:LargeClass = new LargeB();
for (var prop in a) {
b[prop]=a[prop];
}
This won't work if you need constructors for the class, though. And really it's suboptimal... Workaround none the less :)
Oh, by the way, this works because typescript doesn't emit unitialised property/field type declarations for classes--it only uses them for type checking.
I also realise that you can do this without interfaces and just the class construct in a prettier way... I'll leave how to do that as an exercise to readers for now...
you can import your functions from other files than the class itself
here is the example of the class file:
import {func1, func2, func3} from "./functions"
class MyClass {
public foo: string = "bar"
public func1 = func1.bind(this)
public func2 = func2.bind(this)
public func3 = func3.bind(this)
}
Here is the example of one function file:
import {MyClass} from "./MyClass"
export function func1(this: MyClass, param1: any, param2: any){
console.log(this.foo)
...
}
Important note: make sure that every exported function is not an arrow function because you can't do bind(this) on an arrow function
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