Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make the chunk parameter of ReadableStreamDefaultController.enqueue non optional #1682

Open
PeterD1524 opened this issue Feb 2, 2024 · 0 comments

Comments

@PeterD1524
Copy link

PeterD1524 commented Feb 2, 2024

The Web IDL definition specifies an enqueue method for the ReadableStreamDefaultController class with the following signature:

undefined enqueue(optional any chunk);

The chunk parameter is optional which probably is fine since chunk is any.

However, this is a little problematic with TypeScript generics.
Currently, the generated TypeScript interface looks like this:

interface ReadableStreamDefaultController<R = any> {
    enqueue(chunk?: R): void;
}

This allows undefined to be enqueued into the stream while the reader of the stream still expects to read R out of it.

This is demonstrated in the following example:

const stream = new ReadableStream<string>({
  start: (controller) => {
    // currently the signature is
    // ReadableStreamDefaultController<string>.enqueue(chunk?: string | undefined): void
    // undefined is enqueued here
    controller.enqueue();
  },
});

// ReadableStreamDefaultReader<string>
const reader = stream.getReader();

// ReadableStreamReadResult<string>
const result = await reader.read();
if (result.done === false) {
  // result is narrowed down to ReadableStreamReadValueResult<string>

  // TypeScript assumes ReadableStreamReadValueResult<string>.value is string
  // so the compilation will succeed
  // but result.value is actually undefined
  result.value.toUpperCase();
}

To address this, could we consider overriding the chunk parameter to be required?
There are similar issues with TransformStreamDefaultController.enqueue and WritableStreamDefaultWriter.write.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant