如何使用es6-promises与打字稿?
我读this SO question,但很难得到使用打字稿的承诺。希望我们能够做出明确的指导。 这是用于服务器/节点项目。我实际上使用最新的iojs,但将ES5作为输出。如何使用es6-promises与打字稿?
$ tsd query es6-promise --action install --save
$ npm install --save es6-promise
// typescript code:
/// <reference path="../../typings/es6-promise/es6-promise.d.ts"/>
var Promise = require("es6-promise").Promise;
require('es6-promise').polyfill();
function test():Promise {
var p:Promise = new Promise();
return p;
}
这是给错误:
Cannot find name 'Promise'.
//或者:
var p = new Promise<string>((resolve, reject) => {
resolve('a string');
});
//error=> Untyped function calls may not accept type arguments.
什么是从你自己的节点服务器端代码返回无极推荐的方法是什么?
引用:
main.ts
import {Promise} from 'es6-promise';
const p: Promise<string> = new Promise (
(resolve: (str: string)=>void, reject: (str: string)=>void) => {
const a: string = "hello from Promise";
resolve(a);
}
);
p.then((st) => {
console.log(st);
});
tsconfig.json
{
"compilerOptions": {
"target": "es3",
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"noLib": false
},
"filesGlob": [
"./**/*.ts",
"!./node_modules/**/*.ts"
],
"files": [
"./main.ts",
"./typings/es6-promise/es6-promise.d.ts"
]
}
compileandrun.sh
#!/bin/sh
npm install es6-promise
tsd install es6-promise
tsc
node main.js
以下是在V2.1.1 +设置为es5
我能够通过安装es6-promise
,然后加入这个使用与async/await
承诺目标到文件顶部:
global.Promise = require('es6-promise').Promise;
而这到tsconfig.json
"lib": [ "es2015.promise", "es5" ],
使用import { Promise }
形式对我来说其他文库崩溃没有工作(例如:Axios公司)
以下内容添加到package.json
:
"devDependencies": {
"@types/es6-promise": "^0.0.32"
},
"dependencies": {
"es6-promise": "~4.1.0"
}
如果我这样做,是否需要导入'Promise'或者我可以使用它吗? ? –
改变目标到你的tsconfig.json中的“es6”
"compilerOptions": {"target": "es6" }
或安装打字稿的Visual Studio 2015年也能解决这个问题,而不修改tsconfig.json
https://www.microsoft.com/en-us/download/details.aspx?id=48593
我需要填充工具这在不同的框架(具体而言,爱可信);我不需要真正创造我自己的承诺,所以这些解决方案都不适合我。幸运的是,答案很简单,如果隐藏得很好:
import { polyfill } from 'es6-promise'
polyfill();
超级迟到的回应,但我只是想提醒你,你自己是我的前往方法。 TS 2.7.2没有其他框架(例如,没有Angular),es6承诺,然后'polyfill()'是支持IE11的最简单的方式。 谢谢。 – mschofield
非常详细的答案,非常感谢! – dcsan
现在推荐使用'typings'而不是'tsd'吗? –
注意那些使用Angular 2的人:你不需要(也不应该使用)import {Promise}语句,你不需要es6-promise.d.ts,因为它与Angular 2框架捆绑在一起(as无论如何,beta 15都是)。 –