如何使用类型定义使得打字稿类实例可用

时间:2014-09-09 13:45:45

标签: typescript

使用the decomposed class pattern的打字稿定义文件示例:

declare module io {
  interface IOStatic {
    new(name: string): IOInstance;
    name: string;
  }

  interface IOInstance {
    get(): string
  }
}
declare var IO: io.IOStatic;
declare module "IO" {
  export = IO;
}

用于:

/// <reference path='external.d.ts' />
import IO = require('IO');

var x = new IO('John');

工作正常。

问题:如何在类型检查中使用IO实例的类型定义,例如:

getName(io: IO): string {
  return io.get();
}

错误TS4022:类型引用不能引用容器&#39; IO&#39;。 我也应该导出实例定义吗?如果是,怎么样?

1 个答案:

答案 0 :(得分:1)

我不清楚你要做什么,所以如果没有正确回答你的问题,我很抱歉。

io.IOStaticio.IOInstance类型可供您使用,如下所示:

import IO = require('IO');

var x = new IO('John'); 

function getName(io: io.IOInstance): string {
    return io.get();
}

getName(x);

当您致电new IO('John');时,您会收到io.IOInstance类型的对象。