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

为何TypeScript中Interface无法赋值给Json类型而Type可以?

为何Interface转换后无法赋值给Json类型,而Type可以?

先看这段代码:

type Json =
  | null
  | undefined
  | boolean
  | string
  | number
  | Json[]
  | { [k: string]: Json }

interface IJson {
  field: string;
}

type TJson = {
  field: string;
}

// 报错:Type 'IJson' is not assignable to type 'Json'.
const i: Json = {} as IJson

// 正常通过
const t: Json = {} as TJson

核心原因:TypeScript对Interface和Type的索引签名兼容规则不同

  • Type定义的TJson:TypeScript会做「结构兼容性」的隐式推断。TJson的所有属性值(field: string)都属于Json的子类型,因此TypeScript会认为它兼容{ [k: string]: Json }这个带索引签名的类型,能顺利赋值给Json。
  • Interface定义的IJson:TypeScript对Interface的检查更严格,因为Interface是可扩展的(后续可以通过声明合并添加新属性)。哪怕当前IJson的所有属性都符合要求,只要没有显式声明字符串索引签名,TypeScript就不会认为它兼容{ [k: string]: Json }——它担心之后会被添加不符合Json类型的属性,所以拒绝赋值。

验证方法

如果给IJson加上显式的字符串索引签名,就能正常赋值了:

interface IJson {
  field: string;
  [k: string]: Json; // 显式添加索引签名
}

const i: Json = {} as IJson // 不再报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:40:58