简体   繁体   中英

What is the type of a commonjs module imported into a typescript file?

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!

Have you tried typeof ?

import * as fs from "fs";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM