simbro
simbro

Reputation: 3692

Typescript: modules with functions being interpreted as promises

I'm am using an npm module called clear to write a CLI application.

The clear module is very simple:

module.exports = function clear(opts) {
    if (typeof (opts) === 'boolean') {
      opts = { fullClear: opts }
    }

    process.stdout.write('\x1b[0f');
};

So it's a really simple module. However when I call the function in my code, like this:

const clear = import('clear')

clear()

I get the following error message:

This expression is not callable. Type 'Promise<(opts?: ClearOptions) => void>' has no call signatures.ts(2349)

The same is true for any other module that exports functions.

My tsconfig looks like this:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "resolveJsonModule": true,
    "typeRoots": ["./typings", "node_modules/@types"]
  },
  "include": ["./**/*.ts"],
  "exclude": ["node_modules", ".vscode", "./typings"]
}

Were am I going wrong?


Update:

If I change the import statement to const clear = require('clear') then it works perfectly!

Upvotes: 0

Views: 57

Answers (1)

JLRishe
JLRishe

Reputation: 101768

The import function returns a promise, because its execution is deferred. It is used for dynamic imports (e.g. when you want to conditionally import a module based on some condition, or when you have a circular dependency between two or more modules).

It seems that what you actually want is an import statement:

import clear from 'clear';

Upvotes: 2

Related Questions