pan
pan

Reputation: 58

How do I add Blob to Typescript?

I am attempting to save a file with FileSaver, which consequentially needs a Blob format. My app is being written in typescript.

When I tried to do

import * as Blob from "blob";

I received the error

Could not find a declaration file for module 'blob'. '/Users/path/to/project/node_modules/blob/index.js' implicitly has an 'any' type.

Try \npm install @types/blob` if it exists or add a new declaration (.d.ts) file containing `declare module 'blob';``

I cannot just import 'blob' because a @types/blob package does not exist.

I created a declaration file blob.d.ts with these contents

declare module 'blob' {
  function Blob(blobParts[, options]): any
  export = Blob
}

based on the MDN entry on the Blob constructor

This did not solve my issue for the one line of code I need Blob for

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});

it returned the error below

Argument of type '{ type: string; }' is not assignable to parameter of type '[any, any]'. Object literal may only specify known properties, and 'type' does not exist in type '[any, any]'.

This similar question is NOT a duplicate and its answer does not help me since that declaration file does not declare a module and does not export anything.

Upvotes: 3

Views: 9859

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51936

In your tsconfig.json, make sure to include webworker in your lib array:

{
  "compilerOptions": {
    ...
    "lib": ["webworker"],
    ...
  },
  ...
}

Even though it should have already been obvious from the reference links provided above, lib.webworker.d.ts contains the declarations necessary for Blob and related interfaces.

interface Blob {
    readonly size: number;
    readonly type: string;
    slice(start?: number, end?: number, contentType?: string): Blob;
}

declare var Blob: {
    prototype: Blob;
    new(blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;
};

Upvotes: 6

Related Questions