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

TypeScript中如何给同时含嵌套字段和扁平字符串的JSON定义正确类型?

报错原因

你为返回值定义的Record<string, Record<string, string>>类型,约定了所有顶级字段的取值都是「键和值均为字符串的对象」,但实际返回结构中status、upload_id都是字符串类型,和定义的类型规则冲突,因此触发类型不匹配报错。

解决方案

推荐显式定义匹配返回结构的接口类型,既能解决报错也能获得完整的类型校验能力:

// 定义和返回结构匹配的类型
interface UploadResponse {
  status: string;
  upload_id: string;
  url: {
    url: string;
    fields: Record<string, string>
  }
}

// 请求时指定返回值为上面定义的类型
fetch(`https://foo.bar/foo`)
    .then(response => response.json())
    .then((result: UploadResponse) => {
        console.log(result)
        const info = result.url;
        const url: string = info.url;
        const upload_id: string = result.upload_id // 类型校验正常,无报错
    })

如果暂时不想写完整结构,也可以把返回值类型放宽为Record<string, any>,但会丢失大部分类型检查能力,不推荐长期使用。

内容的提问来源于stack exchange,提问作者Stupid.Fat.Cat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:24:00