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

为何同类型定义下interface编译报错而type却正常?

TypeScript interface与type的索引兼容性差异
  • 这本质是TypeScript对interface和type的结构兼容性检查逻辑不同导致的:

    • 用type定义的对象类型,TypeScript会直接做结构匹配:只要TTest的所有属性值都符合目标类型{ [index: string]: boolean }的约束,就允许赋值。
    • 而interface定义的类型,TypeScript会将其视为“带有固定属性集合的接口”。当你把它赋值给带索引签名的类型时,TypeScript会额外校验该接口是否显式声明了对应的索引签名。因为ITest只定义了a: boolean,没有声明[index: string]: boolean,TypeScript会顾虑后续可能有人扩展这个接口,添加不符合索引签名约束的属性(比如新增b: string),因此拒绝赋值操作。
  • 要让interface的代码通过编译,有两种可行方案:

    1. 给接口添加显式的索引签名:
      interface ITest {
        [index: string]: boolean;
        a: boolean;
      }
      const Itest: ITest = { a: true };
      const test: { [index: string]: boolean } = Itest;
      
    2. 使用类型断言跳过兼容性检查:
      const test: { [index: string]: boolean } = Itest as { [index: string]: boolean };
      

内容的提问来源于stack exchange,提问作者饕餮饗食

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:15:42