导入到打字稿文件中的commonjs模块的类型是什么?

时间:2019-08-29 17:27:21

标签: typescript import typescript-typings commonjs

我正在Typescript源中导入CommonJS模块。结果,我收到一个包含模块导出功能的对象。

在我的具体用例中,NodeJS的fs模块的声明将导出声明为(typescript-)模块,而不是类型。我需要该模块的接口声明,以便我可以传递模块对象而不会丢失类型信息或扩展模块。

这就是我想要做的:

import * as fs from "fs";

doSomethingWithFs(fsParameter: InstanceType<fs>) {
    ...
}

这导致

TS2709: Cannot use namespace 'fs' as a type.

有什么方法可以从模块声明中获取类型(除了手动重构类型)?

编辑: @Skovy的解决方案效果很好:

import * as fs from "fs";

export type IFS = typeof fs;

// IFS can now be used as if it were declared as interface:
export interface A extends IFS { ... }

谢谢!

1 个答案:

答案 0 :(得分:1)

您尝试过typeof吗?

import * as fs from "fs";

function doSomethingWithFs(fsParameter: typeof fs) {
  fsParameter.readFile(...);
}