Javascript 为什么Typescript需要fetch()';s`body`属性为可读流<;Uint8Array>;?

Javascript 为什么Typescript需要fetch()';s`body`属性为可读流<;Uint8Array>;?,javascript,typescript,Javascript,Typescript,通过以上内容,我得到: const request: RequestInfo = { method, cache, redirect, headers: {} as Headers, body: null as string | null, }; ... fetch(url, request); 类型“string | null”不能分配给类型“ReadableStream | null”。 类型“string”不可分配给类型“Rea

通过以上内容,我得到:

  const request: RequestInfo = {
    method,
    cache,
    redirect,
    headers: {} as Headers,
    body: null as string | null,
  };

  ...

  fetch(url, request);
类型“string | null”不能分配给类型“ReadableStream | null”。
类型“string”不可分配给类型“ReadableStream | null”。
在TS的类型声明中,有:

Type 'string | null' is not assignable to type 'ReadableStream<Uint8Array> | null'.
  Type 'string' is not assignable to type 'ReadableStream<Uint8Array> | null'.
接口请求初始化{
/**
*一个BodyInit对象或null来设置请求的主体。
*/
body?:BodyInit | null;
}
类型BodyInit=Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string;

为什么它需要
ReadableStream

您显示的定义不太正确,您显示的是
RequestInit
,而不是
RequestInfo
。我所拥有的(以及我在微软的TS定义页面上看到的)是

或者将其强制转换为
任意
,因为这种类型的强制转换相当长。我不认为转换到
any
会在这里造成任何混乱、错误或问题

不一定完全理解您的实际问题,但让我们回答这两种可能性

RequestInfo
类型是用于请求实例的类型,例如

body: 'string' as unknown as ReadableStream<Uint8Array>
您正在创建的对象实际上是
fetch
requestInit
第二个参数,为此,您需要使用
requestInit
类型

const request: RequestInfo = new Request(url, requestInit);

现在,如果您想知道为什么
RequestInit
BodyInit
成员说它可以是
readabstream
,那是因为根据规范,它可以,即使还没有浏览器支持它

interface Request extends Body {
  // No definition for `body` here
  // ...
}
interface Body {
  readonly body: ReadableStream<Uint8Array> | null
  // ...
}
body: 'string' as unknown as ReadableStream<Uint8Array>
const request: RequestInfo = new Request(url, requestInit);
const requestInit: RequestInit = {
  method,
  cache,
  redirect,
  headers: {} as Headers,
  body: null as string | null,
};
...
fetch(url, requestInit);