我正在尝试在TypeScript中使用新的动态import()函数,但是出现以下错误:
TS2712: A dynamic import call in ES5/ES3 requires the ‘Promise’
constructor. Make sure you have a declaration for the ‘Promise’
constructor or include ‘ES2015’ in your--lib
option.
我可以像消息提示那样将ES2015.promise lib包含在我的tsconfig中,但这会使我在使用Bluebird Promise时失去类型安全性.
我知道可以在TypeScript中将Bluebird用于异步/等待,因此我想这也应该以相同的方式工作.
该消息还提到了这一点:
Make sure you have a declaration for the ‘Promise’ constructor or […]
是否可以将Bluebird构造函数声明为TS中的Promise构造函数?
示例代码:
import * as Bluebird from 'bluebird';
// This works
async function exampleAsync(): Bluebird<number> {
const result = await Bluebird.resolve(5);
return result;
}
// This does not
import('jquery').then($=> {
console.log($.fn.jquery);
});
TSConfig:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"removeComments": true,
"sourceMap": true,
"alwaysStrict": true,
"forceConsistentCasingInFileNames": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strictNullChecks": true,
"allowJs": true,
"typeRoots": ["node_modules/@types"],
"lib": ["es5", "dom", "es2015.collection"]
},
"exclude": ["node_modules"]
}
解决方法:
TypeScript正在寻找全球的Promise.代码中包含的内容是在模块(“ bluebird”)中声明的Promise,并在另一个模块中本地使用.
这是使编译错误得以解决并具有可运行代码的最小方法:
test.ts:
import * as Bluebird from 'bluebird';
declare global {
const Promise: {
new <R>(callback: (
resolve: (thenableOrResult?: R | PromiseLike<R>) => void,
reject: (error?: any) => void,
onCancel?: (callback: () => void) => void
) => void): Bluebird<R>;
};
}
import('jquery').then($=> {
console.log($);
});
我已经修改了console.log语句,使其仅输出$,以便上面的代码可以在Node中轻松运行,而不需要浏览器. (在Node中加载jquery时,您将获得一个需要Window实例的构造函数,然后从该实例中构建当您在窗口中加载jquery时立即获得的同一种jQuery对象.因此$.fn.jquery无法访问.)
我正在使用以下tsconfig.json,它们是从您的衍生而来的:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"removeComments": true,
"sourceMap": true,
"alwaysStrict": true,
"forceConsistentCasingInFileNames": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strictNullChecks": true,
"allowJs": true,
"skipLibCheck": true,
"lib": ["es5", "dom", "es2015.collection"]
}
}
您那里有几个不必要的选项,而skipLibCheck是处理@ types / jquery问题所必需的.