Javascript Promise返回{}而不是ImageData(TypeScript)
正在尝试在TypeScript中使用此代码:Javascript Promise返回{}而不是ImageData(TypeScript),javascript,typescript,promise,Javascript,Typescript,Promise,正在尝试在TypeScript中使用此代码: convertURIToImageData(URI) { return new Promise((resolve, reject) => { if (URI == null) { return reject(); } const canvas = document.createElement('canvas'); const context = canvas.getContext('2d');
convertURIToImageData(URI) {
return new Promise((resolve, reject) => {
if (URI == null) { return reject(); }
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const image = new Image();
image.addEventListener('load', () => {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, canvas.width, canvas.height);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
resolve(imageData);
}, false);
image.src = URI;
});}
从Promise返回ImageData但我得到的只是{}
像这样使用它:
this.convertURIToImageData('url').then((img) => {
// do stuff with ImageData
})
获取:
Argument of type '{}' is not assignable to parameter of type 'ImageData'. Type '{}' is missing the following properties from type 'ImageData': data, height, width
{}
是当前TypeScript的回退类型。如果TypeScript无法推断函数返回的类型,它将自动推断{}
。TypeScript无法在您使用它的上下文中推断出img
的类型,因此它推断出{}
,并且无法编译
如果将TypeScript集成到代码编辑器中,只需将鼠标悬停在函数上,就可以确认发生了这种情况,返回类型为Promise
。您可以通过注释函数返回类型轻松解决此问题:
convertURIToImageData(URI): Promise<ImageData> {
convertURIToImageData(URI):承诺{
现在返回类型正确地显示为
Promise
,您的代码应该编译。您如何确定它只是{}
?如果您的目的是获取数据:image
类型返回,您应该使用canvas.toDataURL(“image/png”)
与您想要的图像MIME类型。很难说,因为您实际上还没有添加关键的代码,但我可以想象这是{}
的副本,是TypeScript报告的返回类型,还是运行时的实际值?它实际上是在Angular build/serve中,获取类型为{}的参数“”不可分配给“ImageData”类型的参数。类型“{}'缺少类型'ImageData'的以下属性:数据、高度、宽度,但为什么它不能推断类型?似乎它应该可以工作。我同意这很奇怪,我认为它与使用resolve
和reject
有关,而不是标记函数async
。似乎resolve
是为retu键入的rn{}
而不是出于任何原因使用一些泛型