March 20, 2023

TypeScript - Promise only refers to a type, but is being used as a value

When using Promise in TypeScript code and transpiling, it generates the error:

'Promise' only refers to a type, but is being used as a value here. 
Do you need to change your target library? 
Try changing the 'lib' compiler option to es2015 or later

There could be following reasons/fixes for this issue:

  • Check in tsconfig.json file, if the target property (under compilerOptions) is set to es2015 or later (as suggested in the error message).
    {
        "compilerOptions": {
            "target": "es2015",
        }
    }
    
  • In tsconfig.json file, add lib property (under compilerOptions), and set it values to es2015 or later.
    {
        "compilerOptions": {
            "target": "es2015",
            "lib": ["dom", "es2015", "es5", "es6"],
        }
    }
    
  • A quick work around for this error is just removing the type check for Promise, rather than fixing it. Declar the Promise as a variable with type any.
    declare var Promise: any;
    
  • Try to install @types/node from npm;
    npm instal @types/node
    
  • Please be aware that if you are running the tsc command with a file name, then the compiler will ignore the tsconfig.json file. For example, transpiling the file like this:
    tsc myfile.ts
    
    You can edit the tsconfig.json to include a set of files with files property, e.g:
    {
        "compilerOptions": {
            "module": "commonjs",
            "noImplicitAny": true,
            "removeComments": true,
            "preserveConstEnums": true,
            "sourceMap": true,
            "target": "es2015",
            "lib": ["dom", "es2015", "es5", "es6"],
        },
        "files": [
            "myfile.ts",
            "service1.ts",
            "common.ts",
            "util.ts",
        ]
    }
    

No comments:

Post a Comment