我正在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 { ... }
谢谢!
答案 0 :(得分:1)
您尝试过typeof
吗?
import * as fs from "fs";
function doSomethingWithFs(fsParameter: typeof fs) {
fsParameter.readFile(...);
}