将JavaScript Fetch代码适配TypeScript项目的最简方案及报错解决
解决TypeScript中Fetch请求的类型错误
错误原因
TypeScript对Fetch API的RequestInit参数有严格类型校验:
redirect字段仅允许'follow'、'error'、'manual'这三个字面量类型,原代码中redirect被推断为宽泛的string类型,不符合类型要求- 额外提示:HTTP规范中GET/HEAD请求不应携带body,即使设置也会被Fetch忽略,TS也会对此发出警告
解决方案
有两种常用方式修复类型问题,同时建议修正GET请求带body的不合理写法:
方法1:使用as const锁定字面量类型
通过as const让TS将字符串值识别为具体的字面量类型,而非宽泛的string:
const raw = '你的请求体内容'; // 确保raw变量已定义 const requestOptions = { method: 'GET' as const, // GET请求建议移除body,否则会被忽略 // body: raw, redirect: 'follow' as const, headers: { 'x-mock-response-code': '204', }, }; fetch('https://abcd.mock.pstmn.io/token', requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));
方法2:显式声明RequestInit类型
直接给requestOptions指定RequestInit类型,TS会自动校验所有字段的合法性:
const raw = '你的请求体内容'; const requestOptions: RequestInit = { method: 'GET', // body: raw, redirect: 'follow', headers: { 'x-mock-response-code': '204', }, }; fetch('https://abcd.mock.pstmn.io/token', requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error));
关键修改说明
- 针对
redirect字段:要么用as const锁定字面量类型,要么通过显式类型声明让TS自动匹配合法取值 - 针对body:如果确实需要发送请求体,将请求方法改为
POST并保留body字段;GET请求下建议直接移除body
内容的提问来源于stack exchange,提问作者niko craft
相关产品推荐
相关产品推荐

