Typescript: define a class and its methods in separate files

Is it possible to declare a class in a single file and define its methods in separate files?

I have several classes with many methods, and it would be great if I could expand them a bit.

+5
source share
2 answers

Short answer: Typescript does not support splitting a class definition into multiple files.

Temporary solution . You can define an interface containing class members and two different classes that implement this interface. Then mix the properties from one class to another to create a combined class. For instance:

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 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 will not work if you need constructors for the class. And indeed this is suboptimal ... A workaround nonetheless :)

Oh, by the way, this works because Typescript does not highlight uniform property / field type declarations for classes - it only uses them for type checking.

I also understand that you can do this without interfaces and just make the class more beautiful ... I’ll leave how to do this as an exercise for readers for now ...

+6
source

You can import your functions from files other than the class itself

Here is an example 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 an 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 each exported function is not an arrow function, since you cannot bind (this) to an arrow function

0
source

Source: https://habr.com/ru/post/1437547/


All Articles