是否有办法在typescipt中使用ghost类?

时间:2016-12-05 08:51:55

标签: typescript typescript-typings typescript2.0

我在尝试使用“遗产”时总会遇到问题。来自JavaScript代码的TypeScript 2.0代码。

尽管知道您需要一个类型定义文件(*.d.ts)来执行此操作并阅读“最佳实践”。文章Writing Definition FilesBest Practices

我当前的问题是我想在TypeScript应用程序中使用React/AltTypeScript编译器配置为直接为浏览器发出es5代码(即" target":" es5"在tsconfig.json中)。

有问题的部分是将Action js文件转换为ts。

我跟着Alt recommendations to doing that。示例如下:

/**AltJS is a "ghost module" full of non-instantiable interfaces and typedefs to help you write easier code
 * included in our alt.d.ts type definitions
 */

class AbstractActions implements AltJS.ActionsClass {
 constructor( alt:AltJS.Alt){}
 actions:any;
 dispatch: ( ...payload:Array<any>) => void;
 generateActions:( ...actions:Array<string>) => void;
}

//This class will now compile!!
class SomeCoolActions extends AbstractActions {
 constructor() {
     this.generateActions(
         "firstAction",
         "secondAction",
         "thirdAction",
         "fourthAction
     );
 }
}

这个例子的问题是它将编译但它不起作用。尝试时,我总是在浏览器中收到以下错误消息:

  

未捕获的ReferenceError:未定义AbstractActions(...)

原因也是显而易见的:AbstractActions是一个(抽象的) Ghost类,即它只是让打字稿编译器感到满意。在Alt模块中没有名为AbstractActions的东西。使generateActions工作的所有魔力来自Alt.createActions工厂:

let someCoolActions = alt.createActions<Actions>(SomeCoolActions);

因此,这是我的问题:

  1. 有没有办法修复此问题,即使用AbstractActions幽灵类让TypeScript感到高兴但是有一个虚拟的&#39;实施以保持浏览器的满意度?

  2. 更一般:有没有办法确保我在浏览器执行JS应用程序时为我定义类型定义(* .d.ts)的模块的(遗留)JS实现?< / p>

0 个答案:

没有答案