在另一个文件中扩展一个类

时间:2013-08-27 21:54:54

标签: class typescript

我有一些由工具生成的TypeScript代码。我想将这个类扩展到另一个文件中。从0.9.1.1开始,最好的方法是什么?

我想也许我可以将我的附加功能钉在原型上,但这会产生各种错误(根据编译器的情绪而改变)。

例如:

Foo.ts(由工具生成)

module MyModule {
    export class Dog { }
}

Bar.ts

module MyModule {
    function bark(): string {return 'woof';}

    Dog.prototype.bark = bark;
}

2 个答案:

答案 0 :(得分:1)

您无法在TypeScript中的多个文件之间拆分类定义。但是,typescript了解JavaScript的工作原理,并且可以让你编写idomatic JavaScript类:

module MyModule {
     export function Dog(){};
}

module MyModule {
    function bark(): string {return 'woof';}
    Dog.prototype.bark = bark;
}

Try it online

解决这个问题的一种方法是使用继承:

class BigDog extends Dog{
     bark(){}
}

答案 1 :(得分:0)

我以前遇到过你的问题,但我遇到了一些问题。您可以从basarat的示例中看到,可以将简单函数添加为原型的扩展,但是当涉及静态函数或其他静态值时,您可能希望扩展您的(可能是第三方)类, TSC会警告你,这个方法没有静态定义这样的方法。

我的解决方法是以下小黑客:

module MyModule {
     export function Dog(){};
}

// in the other file
if (typeof MyModule !== 'undefined'){
    Cast<any>(MyModule.Dog).Create = ()=>{return new Dog();};
}

// where Cast is a hack, for TS to forcefully cast types :)
Cast<T>(element:any):T{ return element; } 

这应该将MyModule.Dog强制转换为任何对象,因此允许附加任何类型的属性,函数。

相关问题