Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: define class and its methods in separate files

Tags:

typescript

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.

like image 953
vexator Avatar asked Oct 03 '12 10:10

vexator


2 Answers

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...

like image 166
Michael Sondergaard Avatar answered Nov 12 '22 05:11

Michael Sondergaard


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

like image 29
Kevin Avatar answered Nov 12 '22 06:11

Kevin