【问题标题】:TypeScript issue with node-fetch and trying to omit some properties from RequestInit节点获取的 TypeScript 问题并尝试从 RequestInit 中省略某些属性
【发布时间】:2022-06-24 09:41:15
【问题描述】:

我对 TypeScript 很陌生

我正在尝试编写一个包装器来发送一个看起来像这样的帖子请求

import fetch from 'node-fetch';

async function post(
    address: string,
    url: string,
    body: any,
    headers?: Record<string, string>,
    otherParams?: Omit<RequestInit, 'body' | 'method' | 'headers'>
) {
    const response = await fetch(
        `${address}${url}`,
        {
            method: 'POST',
            body: JSON.stringify(body),
            headers: headers,
            ...otherParams
        }
    );
    return await response.json()
}

目的是让它成为一个方便且易于使用的包装器,因此它不会立即显示otherParams 被接受的内容(因为在大多数情况下它们不是必需的),但如果开发人员想要检查和使用它们 - 他们可以。

上面的编译很好。但我意识到我们并不真正需要 headers 那里,所以我们转移到这样的东西(只是从上面删除了标题的提及):

import fetch from 'node-fetch';

async function post(
    address: string,
    url: string,
    body: any,
    otherParams?: Omit<RequestInit, 'body' | 'method'>
) {
    const response = await fetch(
        `${address}${url}`,
        {
            method: 'POST',
            body: JSON.stringify(body),
            ...otherParams
        }
    );
    return await response.json()
}

但是这会导致编译失败并出现以下错误:

minimal-breaking-example.ts:12:9 - error TS2345: Argument of type '{ signal?: AbortSignal; window?: null; referrer?: string; headers?: HeadersInit; cache?: RequestCache; credentials?: RequestCredentials; ... 6 more ...; body: string; }' is not assignable to parameter of type 'RequestInit'.
  Types of property 'headers' are incompatible.
    Type 'HeadersInit' is not assignable to type 'import("<my local path>/node_modules/node-fetch/@types/index").HeadersInit'.
      Type 'Headers' is not assignable to type 'HeadersInit'.
        Type 'Headers' is missing the following properties from type 'Headers': entries, keys, values, raw, [Symbol.iterator]

 12         {
            ~
 13             method: 'POST',
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
... 
 15             ...otherParams
    ~~~~~~~~~~~~~~~~~~~~~~~~~~
 16         }
    ~~~~~~~~~

也许有人对这里出了什么问题有一些想法?

【问题讨论】:

    标签: typescript node-fetch


    【解决方案1】:

    所以,在写这个问题的时候,我真的想通了。我在这里做一个笔记,以防其他人偶然发现。

    我注意到,当我从 node-fetch 删除导入时,一切正常。我还注意到它专门针对Header 类型,它说它缺少属性:entrieskeysvaluesraw[Symbol.iterator]

    原来fetch 所期望的RequestInit 类型和我一直用来用Omit 创建新类型的全局RequestInit 实际上是两种不同的类型。 fetch 重新定义了使用一些属性扩展它们的全局类型。有趣的是,添加到RequestInit 的属性都是可选的,而添加到Headers 的属性则不是。 fetch.Header 类型首先需要来自全局 Header 的所有属性,即存在 entrieskeysvaluesraw[Symbol.iterator]node-fetch Headersfetch Headers)。

    这里的解决方案是使用fetch.RequestInit而不是RequestInit

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 2018-06-26
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 2012-07-11
      相关资源
      最近更新 更多