【问题标题】:Typescript fetch()'s header type?Typescript fetch() 的标头类型?
【发布时间】:2020-08-20 18:10:01
【问题描述】:

我有类似的东西:

  const request: Partial<Request> = {
    method,
    cache,
    redirect,
    headers: {} as Headers,
  };

  if (...) {
    request.headers['content-type'] = contentType;
  }

但是,TS 抱怨Object is possibly 'undefined'.,可能是因为Partial

如果我不包括Partial&lt;&gt;,我会得到:

Type '{ method: string; cache: RequestCache; redirect: RequestRedirect; headers: Headers; }' is missing the following properties from type 'Request': credentials, destination, integrity, isHistoryNavigation, and 15 more.

为什么 TS 不能推断 headers 已经定义?

【问题讨论】:

  • 你的情况如何?
  • 它会检查它是否不是 GET 请求以及 contentType 是否真实。
  • 两个观察结果:1) 应该使用get() 方法而不是索引签名来访问标头值2) 您仍然可以这样做使用 Partial&lt;Request&gt;,您需要告诉 TS 编译器您确定 headers 使用非空断言运算符(例如 request.headers!.get('content-type'))是非空的。

标签: javascript typescript


【解决方案1】:

而不是Partial&lt;Request&gt;,这将使您可以使用所有属性可选

Pick<Request, "method" | "cache" | "redirect" | "headers">

或定义一个对象并使用它的键从 Request 接口中进行静态类型检查

const request = {
  method: "GET",
  cache: "no-cache" as const,
  redirect: "follow" as const,
  headers: {} as Headers,
};

if (true) {
  request.headers["content-type"] = "text/html";
}


const myRequest: Pick<Request, keyof typeof request> = request;

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 2018-01-17
    • 2021-08-22
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多