Typescript 如何将Blob约束到特定类型
根据,我看到了Typescript 如何将Blob约束到特定类型,typescript,Typescript,根据,我看到了Blob的定义: /** A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user
Blob
的定义:
/** A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. */
interface Blob {
readonly size: number;
readonly type: string;
slice(start?: number, end?: number, contentType?: string): Blob;
}
我希望将此类型限制为坚持特定类型的Blob
在我看来,可能需要a和/或an,但特别是作为TS的新手,我不清楚映射类型的示例是否正在更改所有属性,以及如何正确地约束它
我本以为我可以这样做:
type HTMLBlob = {
[P in keyof Blob]?: Blob[P];
} & { type: 'text/html' }
function handleHTMLBlob(blob : HTMLBlob) {
// ...
}
const blob : HTMLBlob = new Blob(['<b>Test</b>'], { type: 'text/html' });
handleHTMLBlob(blob);
是否有一种方法可以将属性约束到特定的子类型(如果可能的话,最好不使用泛型)?(我也不想重新定义
Blob
(除了type
)的其他属性,因为如果Blob
获得新属性,我希望我的Blob子类型自动继承这些属性。)我想您正在寻找关键字
您希望创建一个新接口(例如HTMLBlob
),并向其添加属性type:'text/html'
。您可以从以前的界面获取所有属性,并可以添加新属性:
接口HTMLBlob扩展Blob{
键入:“text/html”;
}
Blob的类型
不是你想象的那样。。。它只是将与任何HTTP请求一起发送的内容类型头,其中包含此Blob。因此,newblob([“嘿,我只是纯文本”],{type:'application/pdf'})
实际上只是保存一个UTF-8纯文本文件的二进制数据,其中包含传入的文本,它根本不是一个pdf文件。我不确定我是否理解您的意思。MDN上的Blob示例使用与我类似的HTML(或JSON)示例。我不希望您的示例在发送到某个地方以作为PDF处理时起作用。我的观点是,此类型
参数仅在非常特定的情况下使用,例如,当您通过XHR.send(Blob)
发送Blob时,它将用于设置请求的内容类型头;当您将iframe的src设置为指向blob的blobURI时,可能会使用其类型来了解浏览器应该如何解释内容。但是无论如何,这个类型对Blob的内容没有任何影响,因此强制它为固定值是没有意义的。如果你想对Blob(类型)进行反省,它会这样做,例如,对于IndexedDB工具来说,智能地以所见即所得、JSON语法高亮显示HTML Blob内容,等等。好吧,你有你的理由(老实说,我不理解),只要记住,检查这个属性不会告诉你关于内容的任何信息。因此,我不知道从何处收集Blob,但您可能必须仔细检查Blob的内容。这会产生相同的错误,因为Blob
已经有一个现有的type
属性(字符串),TS认为该属性与字符串文字扩展不兼容。(将扩展名设置为readonly
时的结果与原来的相同。)
Type 'Blob' is not assignable to type 'HTMLBlob'.
Type 'Blob' is not assignable to type '{ type: "text/html"; }'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type '"text/html"'.