如何将Blob限制为特定类型

时间:2019-10-11 02:06:20

标签: typescript

https://github.com/microsoft/TypeScript/blob/29becf05012bfa7ba20d50b0d16813971e46b8a6/lib/lib.webworker.d.ts#L641-L646,我看到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;
}

我想限制此类型以坚持使用特定type的Blob。

在我看来,可能需要一个Mapped Type和/或intersection type,但是特别是作为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);

但是操场报告:

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"'.

是否可以将此处的属性限制为特定的子类型(如果可能的话,最好不使用泛型)? (我也不想重新定义Blob的其他属性(除type之外,因为如果Blob获得新属性,我希望Blob子类型自动继承那些属性。)< / p>

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找extends关键字。

您要创建一个新界面(例如HTMLBlob)并向其中添加属性type: 'text/html'。您可以从以前的界面中获得所有属性,并可以添加新属性:

interface HTMLBlob extends Blob {
  type: 'text/html';
}
相关问题