“ReadableStream<any>”类型的参数不可分配给“ReadableStream”类型的参数

Nas*_*gar 6 javascript stream node.js typescript

我想获得一个可读形式的 Blob。

import {Readable} from 'stream';

const data: Blob = new Blob( );
const myReadable: Readable = (new Readable()).wrap(data.stream());
myReadable.pipe(ext);
Run Code Online (Sandbox Code Playgroud)

我收到此错误

ERROR in src/app/features/recorder/components/record-panel/record-panel.component.ts:80:38 - error TS2345: Argument of type 'ReadableStream<any>' is not assignable to parameter of type 'ReadableStream'.
  Type 'ReadableStream<any>' is missing the following properties from type 'ReadableStream': readable, read, setEncoding, pause, and 22 more.
Run Code Online (Sandbox Code Playgroud)

我使用 Node 14 angular 10 和 typescript

Lin*_*ste 29

此代码中有两种不同的定义ReadableStream,彼此不兼容。


Blob来自 DOM 类型。 Blob.stream() 返回aReadableStream<any>的定义lib.dom.d.ts

interface ReadableStream<R = any> {
    readonly locked: boolean;
    cancel(reason?: any): Promise<void>;
    getReader(): ReadableStreamDefaultReader<R>;
    pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;
    pipeTo(dest: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
    tee(): [ReadableStream<R>, ReadableStream<R>];
}
Run Code Online (Sandbox Code Playgroud)

GitHub 源码


Readable.wrap() ReadableStream期望使用 NodeJS 定义中的a进行调用@types/node/globals.ts

interface ReadableStream extends EventEmitter {
    readable: boolean;
    read(size?: number): string | Buffer;
    setEncoding(encoding: BufferEncoding): this;
    pause(): this;
    resume(): this;
    isPaused(): boolean;
    pipe<T extends WritableStream>(destination: T, options?: { end?: boolean; }): T;
    unpipe(destination?: WritableStream): this;
    unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void;
    wrap(oldStream: ReadableStream): this;
    [Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>;
}
Run Code Online (Sandbox Code Playgroud)

GitHub 源码


您的代码尝试将 DOM 分配ReadableStream给需要 NodeJS 的函数ReadableStream。您会收到一条错误消息,告诉您此 Node 版本需要的所有属性在 DOM 版本变量中不存在data.stream()

  • @liamlows我认为你可以使用类型断言?`someVar as NodeJS.ReadableStream` 或可能 `someVar asknown as NodeJS.ReadableStream` (3认同)