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

Consider making WritableStreamDefaultWriter.write() contravariant #59012

Open
cdauth opened this issue Jun 25, 2024 · 0 comments
Open

Consider making WritableStreamDefaultWriter.write() contravariant #59012

cdauth opened this issue Jun 25, 2024 · 0 comments
Labels
Bug A bug in TypeScript Help Wanted You can do this
Milestone

Comments

@cdauth
Copy link

cdauth commented Jun 25, 2024

⚙ Compilation target

esnext

⚙ Library

dom

Missing / Incorrect Definition

WritableStreamDefaultWriter.write(chunk)

Sample Code

const test: WritableStream<{ a: string }> = new WritableStream<{ a: string; b: string }>();

The above does not raise a type error. test.getWriter().write({ a: "string" }) will not show an error, even though the underlying stream expects b properties on the chunks. A variation of the problem is this:

const writable = new WritableStream<{ a: string; b: string }>();
new ReadableStream<{ a: string }>().pipeTo(writable); // No error

WritableStream<A> and WritableStream<B> differ in the signature of their getWriter().write(chunk) method. Because WritableStreamDefaultWriter.write(chunk) is a method, it is bivariant, leading to the above examples to pass.

Other than for example Array, WritableStream is only ever used for writing, never for reading, so as far as my understanding goes, bivariance does not have any use here. This is why I would suggest to change the typing of WritableStream to make it contravariant, to make the examples above raise errors. One way to achieve that would be to declare WritableStreamDefaultWriter.write() as a function property instead of a method, that would solve the problem at least in strict mode:

    write: (chunk?: W) => Promise<void>;

Although I am not sure whether that would have any other implications.

As a workaround, I use the following code:

const write = Symbol();
declare global {
	interface WritableStreamDefaultWriter<W = any> {
		[write]: (a: W) => void;
	}
}

Some more details about this can also be found on StackOverflow.



### Documentation Link

_No response_
@RyanCavanaugh RyanCavanaugh added Bug A bug in TypeScript Help Wanted You can do this labels Jun 26, 2024
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Jun 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Help Wanted You can do this
Projects
None yet
Development

No branches or pull requests

2 participants