microsoft / TypeScript-DOM-lib-generator

Tool for generating dom related TypeScript and JavaScript library files
Apache License 2.0
601 stars 418 forks source link

ReadableStream.from() method? #1691

Open karlhorky opened 5 months ago

karlhorky commented 5 months ago

Hi, first of all, thanks for your work on these type declarations, they are invaluable for working with web standards APIs.

It seems as if the following is not yet supported in TS 5.3.3 (also fails in Beta and Nightly):

ReadableStream.from(['a', 'b']);
//             ^^^^? Property 'from' does not exist on type '{
//                     new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response;
//                     prototype: Response;
//                     error(): Response;
//                     json(data: any, init?: ResponseInit | undefined): Response;
//                     redirect(url: string | URL, status?: number | undefined): Response;
//                   }'.

Maybe a similar PR is needed to update the types to the WebIDL Streams spec like @MattiasBuelens did in 2020 in https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/890?

Or is this not supported yet because only 3 runtimes (Firefox, Deno and Node.js) support this?

I can also re-submit this in https://github.com/microsoft/typescript if that makes more sense.

MattiasBuelens commented 5 months ago

I think you meant ReadableStream.from() in your example code, rather than Response.from(). 😉

Or is this not supported yet because only 3 runtimes (Firefox, Deno and Node.js) support this?

Correct, this is still missing browser support. At the moment, only 1 browser engine (Firefox's Gecko engine) has implemented ReadableStream.from(). (Node.js and Deno don't count, since they aren't browser engines.)

Usually, I would suggest to add a type definition to your own code for now. Unfortunately, that doesn't work in this case, since you can't override the type of declare var ReadableStream (playground)... 😕

Off topic For the JavaScript types, we usually do things like: ```typescript interface Array { // instance properties and methods } interface ArrayConstructor { // constructors, static properties and methods } declare var Array: ArrayConstructor; ``` That way, users can augment `ArrayConstructor` in their own code, and have extra static `Array` methods that way. Unfortunately, we don't do this for any of the DOM types... (Presumably because it'd add a ton of extra types?)

So for now, you have to add an explicit cast wherever you want to use the extra methods... (playground)

type ReadableStreamExt = (typeof ReadableStream) & {
    from<R>(asyncIterable: Iterable<R> | AsyncIterable<R>): ReadableStream<R>;
};

// 😬
(ReadableStream as ReadableStreamExt).from(['a', 'b']);

You can also go click the "+1" button on the Chromium issue, so maybe someone will pick it up. 😁