javascript - Promise 返回 {} 而不是 ImageData (TypeScript)

标签 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');
      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> {

现在返回类型正确显示为 Promise<ImageData>并且您的代码应该可以编译。

关于javascript - Promise 返回 {} 而不是 ImageData (TypeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55026701/

相关文章:

javascript - Vue i18n with TypeScript : "Property ' $t' does not exist on type 'VueConstructor' . 时出错“。我该如何修复它?

javascript - VueJS/Typescript - 找不到模块 './components/Navigation' 或其相应的类型声明

promise - Axios 拦截器 : how to throw errors in the onFulfill?

javascript - 为什么这会抛出 SyntaxError?

javascript - 使用 AWS javascript sdk 出现 No Access-Control-Allow-Origin 错误

javascript - 我的表在页面重新加载时更新为空行

javascript - 使用 webdriverjs 和 mocha/chai 等待页面加载

javascript - 返回链式 Promise 的函数的返回类型

javascript - 在异步/等待函数完成之前执行的代码?

javascript - 在javascript中将对象传递给html中的函数?