题
是否可以在一个文件中声明一个类并在单独的文件中定义其方法?
我有一个很多的方法,如果我可以把它们传播出来,那就太好了。
解决方案
简短答案:打字条不支持将类定义分成几个文件。
解决方法:您可以定义包含类成员的接口,以及实现该接口的两个不同类。然后将属性从一个类混在一起,以制作组合类。例如:
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
}
.
使用.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];
}
.
但是,如果您需要类的构造函数,则不会起作用。真的是次优......解决方法没有:)
哦,顺便说一下,这是因为类型签名没有发出类的单层属性/字段类型声明 - 它只使用它们进行类型检查。
我也意识到您可以在没有接口的情况下做到这一点,只是以一种更漂亮的方式进行阶级构建......我会留下如何这样做作为读者的锻炼...
其他提示
您可以将函数从其他文件导入比类本身
这是类文件的示例:
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)
}
.
这是一个函数文件的示例:
import {MyClass} from "./MyClass"
export function func1(this: MyClass, param1: any, param2: any){
console.log(this.foo)
...
}
.
重要说明:确保每个导出的函数都不是箭头函数,因为您无法在箭头函数上绑定(此)
不隶属于 StackOverflow