TypeScript 索引签名继承了普通类型

时间:2021-07-06 18:03:52

标签: typescript

为什么我的代码出现错误?没有 sum 属性的代码运行良好。

type IData = {
  [position: string]: {
    [year: number]: {
      [month: string]: {
        val: number
        id: string
        currency: string
      }
      sum: number
    }
  }
}

ErrorDialog And why this works?

1 个答案:

答案 0 :(得分:2)

问题是用索引类型定义的对象中的其他(非索引)键必须具有与索引字段兼容的类型。

您可以将类型重写为:

type IData = {
  [position: string]: {
    [year: number]: {
      [month: string]: {
        val: number
        id: string
        currency: string
      } | number // notice added | number
      sum: number
    }
  }
}

playground link

传递有关 indexable types 的打字稿规则。

相关问题