I get: [ts] 'Promise' only refers to a typ

2020-03-26 06:29发布

问题:

I'm taking an Angular2 course and following along. Everything I have been doing thus far for all the other exercise has worked fine until I got to creating this custom validator and this Promise code. Makes no sense to me why this would occur now.

I get: [ts] 'Promise' only refers to a type, but is being used as a value here.

Can't seem to resolve this. I get my error even without adding in the setTimeout function.

Per a suggestion from someone elsewhere. I added to the tsconfig.json: "compilerOptions": { ... "types" : [ "core-js" ] }

But I still get the error.

Using Visual Studio code: Version 1.10.1. OS: Windows 10 Pro.

Here's my code:

import {Control} from 'angular2/common';

export class UsernameValidators 
{
    static shouldBeUnique(control: Control) 
    {
       return new Promise((resolve, reject) =>
       {            
          setTimeout(function()
          {
             if (control.value == "Dan")
                resolve({ shouldBeUnique: true });
             else
                resolve(null);
          }, 1000);
       });
   }
}

Here's the course that I am taking and a screen shot of what I am being instructed to do. The intelliSense is different from mine. It works fine and they do not get the error I get.

Here's the courses end result.

回答1:

You need to target ES6, or else use a polyfill library like bluebird. If you are targeting ES5 in the compiler output, then it will fail like this because ES5 has no Promises.



回答2:

Possible duplicate of #43546088 (only if you're already using DefinitelyTyped): in case you aren't, I would suggest you to try and use them so you can normalize your compiler references and possibly fix the issue.

If you're using it, I suggest you to read this Github thread for an extensive analysis of the problem and also some workaround. To quickly recap the (IMHO) best one of them, assuming that you have this in your package.json file:

  "scripts": {
    "postinstall": "typings install dt~core-js --global"
  }

Change it in the following way:

  "scripts": {
    "postinstall": "typings install dt~core-js@0.9.7+20161130133742 --global"
  }

So you'll force VS to get a unaffected version/build of the core-js definitions file(s). However, is highly recommended to remove the explicit version+build reference as soon as the issue will be released.

For further info regarding this issue, you can also read this post on my blog.



标签: angular