0
votes

I am importing a CommonJS module in a Typescript source. As a result I receive an object containing exported features of the module.

In my concrete use case the declarations for NodeJS's fs module declare the exports as (typescript-) module, not as type. I need an interface declaration for that module, so that I can pass the module object without loosing the type information or to extend the module.

Here is what I want to do:

import * as fs from "fs";

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

This results in

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

Is there any way to get a type from a module declaration (other than manually refactoring the typings)?

EDIT: @Skovy's solution works perfectly:

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 { ... }

Thanks!

1

1 Answers

1
votes

Have you tried typeof?

import * as fs from "fs";

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