如何在原生 ES6 Promise 中使用 Typescript [英] How to use Typescript with native ES6 Promises

查看:34
本文介绍了如何在原生 ES6 Promise 中使用 Typescript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Typescript 的完全初学者,想知道是否可以在 Typescript 中使用 ES6 承诺,以及我必须做些什么才能让它们工作.我正在运行节点 0.11.14 并且在编译过程中出现错误找不到名称 'Promise'"

I'm a complete beginner to Typescript and am wondering if it's possible to use ES6 promises in Typescript and what I would have to do to get them to work. I'm running node 0.11.14 and am getting an error during compilation "Cannot find name 'Promise'"

推荐答案

当前的 lib.d.ts 中没有定义 promise,因此您需要一个额外的定义文件,这就是为什么会出现编译错误的原因.

The current lib.d.ts doesn't have promises in it defined so you need a extra definition file for it that is why you are getting compilation errors.

例如,您可以使用(如@elclanrs 所说)使用es6-promise 包和来自DefinitelyTyped 的定义文件:es6-promise 定义

You could for example use (like @elclanrs says) use the es6-promise package with the definition file from DefinitelyTyped: es6-promise definition

然后您可以像这样使用它:

You can then use it like this:

var p = new Promise<string>((resolve, reject) => { 
    resolve('a string'); 
});

edit 在针对 ES6(使用 TypeScript 编译器)时,您可以在没有定义的情况下使用它 - 请注意,您仍然需要 Promise 存在于当然的运行时中(因此它在旧浏览器中不起作用:))将以下内容添加/编辑到您的 tsconfig.json :

edit You can use it without a definition when targeting ES6 (with the TypeScript compiler) - Note you still require the Promise to exists in the runtime ofcourse (so it won't work in old browsers :)) Add/Edit the following to your tsconfig.json :

"compilerOptions": {
    "target": "ES6"
}

编辑 2当 TypeScript 2.0 出来时,事情会有所改变(虽然上面仍然有效)但定义文件可以直接使用 npm 安装,如下所示:

edit 2 When TypeScript 2.0 will come out things will change a bit (though above still works) but definition files can be installed directly with npm like below:

npm install --save @types/es6-promise -

edit3使用类型的更多信息更新答案.

edit3 Updating answer with more info for using the types.

创建一个 package.json 文件,其中仅包含 { } 作为内容(如果您还没有 package.json.调用 npm install --save @types/es6-promisetsc --init.第一个 npm install 命令将更改您的 package.json 以包含 es6-promise 作为依赖项.tsc --init 将为您创建一个 tsconfig.json 文件.

Create a package.json file with only { } as the content (if you don't have a package.json already. Call npm install --save @types/es6-promise and tsc --init. The first npm install command will change your package.json to include the es6-promise as a dependency. tsc --init will create a tsconfig.json file for you.

您现在可以在打字稿文件 var x: Promise; 中使用承诺.执行 tsc -p . 来编译你的项目.您应该没有错误.

You can now use the promise in your typescript file var x: Promise<any>;. Execute tsc -p . to compile your project. You should have no errors.

这篇关于如何在原生 ES6 Promise 中使用 Typescript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆