Typescript:在单独的文件中定义类及其方法

vex*_*tor 6 typescript

是否可以在一个文件中声明一个类并在单独的文件中定义它的方法?

我有一些有很多方法的课程,如果我可以将它们分散一点,那将会很棒.

Mic*_*ard 6

简答: Typescript不支持将类定义拆分为多个文件.

解决方法:您可以定义包含该类成员的接口,以及实现该接口的两个不同类.然后将一个类的属性混合到另一个类,以组合类.例如:

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";
   }
}
Run Code Online (Sandbox Code Playgroud)

LargeClass.b.ts

class LargeB implements LargeClass {
   methodA() {
     return "Foo";
   }
   methodB: () => string; // not implemented, needed since otherwise we don't extend LargeClass
}
Run Code Online (Sandbox Code Playgroud)

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];
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要类的构造函数,这将不起作用.实际上它不是最理想的......解决方法一点也不错:)

哦,顺便说一句,这是有效的,因为typescript不会为类发出unitialised属性/字段类型声明 - 它只使用它们进行类型检查.

我也意识到你可以在没有接口的情况下做到这一点,只是以更漂亮的方式构建类...我现在将把这个作为练习留给读者...


小智 5

您可以从类本身以外的其他文件中导入您的函数

这是类文件的示例:

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)
}
Run Code Online (Sandbox Code Playgroud)

以下是一个函数文件的示例:

import {MyClass} from "./MyClass"

export function func1(this: MyClass, param1: any, param2: any){
   console.log(this.foo)
   ...
} 
Run Code Online (Sandbox Code Playgroud)

重要说明:确保每个导出的函数都不是箭头函数,因为您不能对箭头函数执行 bind(this)