【发布时间】: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.name 和 blob.url 我得到 ts 错误:
Cannot assign to 'name' because it is a read-only property.ts(2540)
【问题讨论】:
-
为什么要覆盖现有的
Blob类型? -
@RobertoZvjerković 添加名称和网址
-
@RobertoZvjerković developer.mozilla.org/en-US/docs/Web/API/Blob
-
但是 Blob 没有名称和 url,不能只添加到类型中
标签: typescript next.js blob