You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic React TypeScript:类型不兼容错误及Base64响应体存储问题

问题解决:TypeScript类型错误与Base64文件保存

错误原因

你错误地将response.body断言为FetchData[]数组类型,但实际它是文件的Base64字符串,导致后续把数组赋值给string类型变量base64File时触发类型不匹配错误:Type 'FetchData[]' is not assignable to type 'string'。

解决方案

1. 修正类型断言

直接将response.body断言为string类型,匹配其实际的Base64字符串值:

2. 调整后的完整代码

fetchCustom(store.apiURL, {
    trtyp: 'file_download',
    seskey: store.userSessionKey,
    id: item.iddoc
}).then(response => {
    // 断言response.body为string类型,对应Base64字符串
    const base64File: string = response.body as string;
    console.log('获取到的Base64:', base64File);

    Filesystem.writeFile({
        path: "filename.txt",
        data: base64File,
        directory: Directory.Documents,
    }).then(() => {
        console.log('文件保存成功');
    }).catch(error => {
        console.log('文件保存失败:', error.message);
    });

}).catch(error => {
    console.log('请求接口失败:', error.message);
});

特殊情况补充

如果接口返回的是包含Base64字符串的FetchData[]数组(比如数组元素中的某个字段存储Base64),则需要从数组中提取对应字段。例如假设第一个元素的fileContent字段是Base64:

const data = response.body as FetchData[];
const base64File: string = data[0].fileContent as string;

但根据你的描述,response.body本身就是Base64字符串,因此优先使用第一种直接断言为string的方案。

内容的提问来源于stack exchange,提问作者DavidDunham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 16:22:46