【发布时间】: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