【问题标题】:Using Blob in typescript?在打字稿中使用 Blob?
【发布时间】:2021-12-05 15:37:00
【问题描述】:

我声明了全局 Blob:

declare global {
  interface Blob {
    prototype: Blob;
    new (name: string, url: string): Blob;
  }
}

这在这里有效:

export const blobToFile = (blob: Blob) => {
  let file: File | null = null;
  if (typeof window !== "undefined") {
    file = new File([blob], blob.name, { type: blob.type });
  }  
  return file ? file : null;
};

但它在 2 个地方给了我错误。第一:

   const [croppedImg, setCroppedImg] = useState<Blob | null>(null);

    <img
            src={(croppedImg && croppedImg.url) || selectedImg.src}
            alt=""
    ></img>

我收到这个 ts 错误:

      "Property 'url' does not exist on type 'Blob' "

第二个问题是当我在画布上写 blob 时:

return new Promise((resolve, reject) => {
    canvas.toBlob(
      (blob) => {
        if (!blob) {
          reject("Canvas is empty");
          return;
        }
        blob.name = fileName;
        const fileUrl = window.URL.createObjectURL(blob);
        blob.url = fileUrl;
        resolve(blob);
      },
      "image/jpeg",
      1
    );
  });

对于 blob.nameblob.url 我得到 ts 错误:

         Cannot assign to 'name' because it is a read-only property.ts(2540)

【问题讨论】:

标签: typescript next.js blob


【解决方案1】:

使用您的自定义成员创建新的 blob 类型:

interface BlobV2 extends Blob {
  name?: string
  url?: string
}

然后使用一些技术将属性复制到您的新数据结构中: 以最简单的方式进行说明。

 const _blob: BlobV2 = { ... blob }
_blob.name = fileName
_blob.url = fileUrl

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-14
    • 2017-08-20
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    相关资源
    最近更新 更多