Una*_*dra 7 javascript http-headers typescript reactjs fetch-api
我想创建一个自定义fetchServer方法,在执行实际的fetch.
最后,这个方法使用了fetchJavascript 的通用方法,它具有以下签名:
function fetch(input: RequestInfo | URL, init?: RequestInit | undefined): Promise<Response>
Run Code Online (Sandbox Code Playgroud)
所以,我是fetchServer这样写的:
export const fetchServer = async <T>(
url: string,
options: any = {},
): Promise<T> => {
...
const alteredOptions = { ...options, /* my custom code */ };
const rawResponse = await fetch(url, { ...alteredOptions});
...
};
Run Code Online (Sandbox Code Playgroud)
但是,正如您所看到的,我正在使用anyfor options,因为我无法RequestInit从任何地方成功导入该类型。
我已经读过这个问题,但它来自apollo包(我没有使用)并且没有解决。
我可以尝试自己声明它,但同样的情况也会发生在body和headers属性(具有BodyInit和HeadersInit类型)上。
我也尝试直接引用它,但 ESlint 会抛出错误,因为它undefined和 VSCode 似乎无法正确导入它(尽管它会自动完成它)。
interface RequestInit
'RequestInit' is not defined : eslint(no-undef)
Run Code Online (Sandbox Code Playgroud)
我使用的是 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"
},
Run Code Online (Sandbox Code Playgroud)
我应该如何键入我的options参数,以便它扩展方法RequestInit的类型参数fetch,并且我能够使用我自己的属性扩展它?
我遇到了同样的问题。事实证明,这并不像我一开始认为的那样是类型错误。"DOM"Typescript 具有作为 tsconfig.json 中的库包含的类型信息
{
“编译器选项”:{
...
“lib”:[...,“DOM” ],
}
但这个错误实际上只是 eslint 的问题,它没有被视为RequestInit全局类型。
快速解决方法是将以下内容添加到引用它的 .ts 文件中。
/* global RequestInit */
Run Code Online (Sandbox Code Playgroud)
您还可以将其作为全局添加到 eslintrc 文件中,以在项目范围内执行相同的操作。
"globals": {
"RequestInit": true
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1648 次 |
| 最近记录: |