const request: RequestInfo = {
method,
cache,
redirect,
headers: {} as Headers,
body: null as string | null,
};
...
fetch(url, request);
With the above, I get:
Type 'string | null' is not assignable to type 'ReadableStream<Uint8Array> | null'.
Type 'string' is not assignable to type 'ReadableStream<Uint8Array> | null'.
In TS's type declarations, there's:
interface RequestInit {
/**
* A BodyInit object or null to set request's body.
*/
body?: BodyInit | null;
}
type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream<Uint8Array> | string;
Why is it expecting ReadableStream<Uint8Array>
?
const request: RequestInfo = {
method,
cache,
redirect,
headers: {} as Headers,
body: null as string | null,
};
...
fetch(url, request);
With the above, I get:
Type 'string | null' is not assignable to type 'ReadableStream<Uint8Array> | null'.
Type 'string' is not assignable to type 'ReadableStream<Uint8Array> | null'.
In TS's type declarations, there's:
interface RequestInit {
/**
* A BodyInit object or null to set request's body.
*/
body?: BodyInit | null;
}
type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream<Uint8Array> | string;
Why is it expecting ReadableStream<Uint8Array>
?
2 Answers
Reset to default 7Not sure to pletely understand your actual question, but let's answer both possibilities.
The RequestInfo
type is the one used for a Request instance, e.g
const request: RequestInfo = new Request(url, requestInit);
The object you are creating is actually the requestInit
second parameter of fetch
, and for this you need to use the RequestInit
type.
const requestInit: RequestInit = {
method,
cache,
redirect,
headers: {} as Headers,
body: null as string | null,
};
...
fetch(url, requestInit);
Now if you were wondering why the RequestInit
's BodyInit
member says it can be a ReadablStream<Uint8Array>
, that's because per specs it can, even though no browser supports it yet and the specs are not really bullet-proof yet.
The definitions you show are not quite right, you show RequestInit
, not RequestInfo
. What I have (and what I could see on microsoft pages with TS definitions) is this
type RequestInfo = Request | string
interface Request extends Body {
// No definition for `body` here
// ...
}
interface Body {
readonly body: ReadableStream<Uint8Array> | null
// ...
}
So it's clear, why the piler plains. But it's not clear to me, why the definition is like so, because I'm sure it's possible to pass string
as the body
of a request. I think you will have to cast it to readable stream:
body: 'string' as unknown as ReadableStream<Uint8Array>
Or just cast it to any
, because this type cast is pretty long. I don't think casting to any
will cause any confusion, errors or problems here