代码之家  ›  专栏  ›  技术社区  ›  Brett Zamir

如何将Blob约束到特定类型

  •  0
  • Brett Zamir  · 技术社区  · 6 年前

    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;
    }
    

    我希望将这种类型限制为坚持使用特定类型的Blob type

    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子类型自动继承这些属性。)

    0 回复  |  直到 6 年前
        1
  •  0
  •   a1300    6 年前

    我想你是在找 extends 关键词。

    HTMLBlob )并添加属性 type: 'text/html'

    interface HTMLBlob extends Blob {
      type: 'text/html';
    }
    
    推荐文章