简体   繁体   中英

How can I resolve the error related error:TS2705 in typescript

error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your --lib option.

import * as Hapi from 'hapi';

import * as IConfig from 'config';
const config = JSON.parse(JSON.stringify(IConfig));

const serverConnections = config.server,
    server: Hapi.Server = new Hapi.Server(serverConnections);

export module Server {
  export const start = async () => {
    server.route({
      path: '/',
      method: 'GET',
      handler(request, h) {
        return "hello!!!"
      },
    });

    console.log('serverstart')
    server.start();
  }
}

When you start a minimal new TypeScript project, your tsconfig.json file will be close to empty. That means the compiler does not know what libraries will be available on your chosen platform. In essence, you'll have more or less a bare-bones version of javascript to play with and whatever library types you npm install into your dependencies. By barebones, I mean there are some default libraries included. As per the time of writing this, the documentation states:

a default list of libraries are injected. The default libraries injected are:

  • For --target ES5: DOM,ES5,ScriptHost
  • For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

Because you've got some code in your sample code that uses the async keyword - which is syntactic sugar around the Promise API - TypeScript is going to try and compile it down to Promises. However, you haven't yet listed the libraries your platform can support.

In order to tell the compiler what APIs you want to target, you need to give it some hints.

There are two ways of doing this:

  1. Add "lib":["es2015"] to your tsconfig.json file
  2. Run the typescript cli command with the --lib flag, like so: tsc --lib ES2015

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