Typescript – 如何导入和使用 fetch 的 RequestInit 类型?

huangapple go评论77阅读模式
英文:

Typescript - How to import and use RequestInit type from fetch?

问题

我想创建一个自定义的fetchServer方法,在我的React应用程序中,在执行实际的fetch之前,我可以操作不同的参数(如URL、头部等)。

这个方法最终使用了JavaScript中的常见fetch,它的签名如下:

function fetch(input: RequestInfo | URL, init?: RequestInit | undefined): Promise<Response>

所以,我这样编写了我的fetchServer

export const fetchServer = async <T>(
  url: string,
  options: any = {},
): Promise<T> => {
  ...
  const alteredOptions = { ...options, /* 我的自定义代码 */ };
  const rawResponse = await fetch(url, { ...alteredOptions});
  ...
};

然而,正如你所看到的,我对options使用了any,因为我无法成功地从任何地方导入RequestInit类型。

我已经阅读了这个问题,但它来自apollo包(我没有使用它)而且没有解决。

我可以尝试自己声明它,但是同样的情况也发生在bodyheaders属性上(它们具有BodyInitHeadersInit类型)。

我也尝试直接引用它,但是ESLint会抛出一个错误,因为它是undefined,而VSCode似乎无法正确导入它(尽管它会自动完成它)。

interface RequestInit
'RequestInit' is not defined: eslint(no-undef)

我使用的是Typescript v4.6.3,这是我的tsconfig.json设置:

"compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "downlevelIteration": true,
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
}

我应该如何为我的options参数定义类型,以便它扩展fetch方法的RequestInit类型参数,以便我能够扩展它并添加我的自定义属性?

英文:

I want to create a custom fetchServer method in which I can manipulate the different parameters (such as the URL, headers, and so on) in my React application before performing the actual fetch.

This method, at the end, uses the common fetch from Javascript, which has the following signature:

function fetch(input: RequestInfo | URL, init?: RequestInit | undefined): Promise&lt;Response&gt;

So, I've written my fetchServer this way:

export const fetchServer = async &lt;T&gt;(
  url: string,
  options: any = {},
): Promise&lt;T&gt; =&gt; {
  ...
  const alteredOptions = { ...options, /* my custom code */ };
  const rawResponse = await fetch(url, { ...alteredOptions});
  ...
};

However, as you can see, I'm using any for options, because I'm unable to import successfully the RequestInit type from anywhere.

I've read this issue, but it's from apollo package (which I'm not using) and it's not solved.

I can try to declare it myself, but then the same happens with body and headers properties (which have BodyInit and HeadersInit types).

I've also tried to reference it directly, but ESlint throws an error because it's undefined and VSCode seems unable to import it correctly (although it autocompletes it).

interface RequestInit
&#39;RequestInit&#39; is not defined : eslint(no-undef)

I'm using Typescript v4.6.3, and these are my tsconfig.json settings:

&quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;es5&quot;,
    &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;],
    &quot;downlevelIteration&quot;: true,
    &quot;allowJs&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;strict&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;noFallthroughCasesInSwitch&quot;: true,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;resolveJsonModule&quot;: true,
    &quot;isolatedModules&quot;: true,
    &quot;noEmit&quot;: true,
    &quot;jsx&quot;: &quot;react-jsx&quot;
},

How should I type my options parameter so that it extends the RequestInit type parameter of fetch method, and I'm able to extend it with my own properties?

答案1

得分: 3

我遇到了相同的问题。原来它并不像我一开始以为的那样是一个类型错误。Typescript 在 tsconfig.json 中作为库包含了 &quot;DOM&quot; 的类型信息。

{
  "compilerOptions": {
    ...
    "lib": [..., "DOM"],
  }
}

但这个错误实际上只是 eslint 的问题,它无法识别 RequestInit 作为全局类型。

一个快速的解决方法是在引用它的 .ts 文件中添加以下内容:

/* global RequestInit */

你也可以将它添加到你的 eslintrc 文件中,以在整个项目中实现相同的效果。

"globals": {
  "RequestInit": true
}
英文:

I ran into the same issue. Turns out it was not a type error like I thought it was at first. Typescript has the type info from &quot;DOM&quot; being included as a lib in tsconfig.json

<pre>
{
"compilerOptions": {
...
"lib": [..., <b>"DOM"</b>],
}
</pre>

But that error was really only something wrong with eslint and it not seeing RequestInit as a global type.

A quick workaround is to add the following to the .ts file that referenced it.

/* global RequestInit */

You could also add it as a global to your eslintrc file to do the same thing project wide.

&quot;globals&quot;: {
  &quot;RequestInit&quot;: true
}

huangapple
  • 本文由 发表于 2023年6月1日 22:50:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383168.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定