首页 > 解决方案 > Typescript — 确保对象 prop 键与 prop 值相同

问题描述

我需要输入以下对象结构:

const entities = {
  abc: {
    id: 'abc'
  },
  def: {
    id: 'def'
  }
}

每个对象的 prop 键都需要匹配其对应的id.


我试过这样做:

interface EntitiesMap<E extends Entity> {
  [K in E['id']]: E;
}

interface Entity {
  id: string;
}

但这并不能确保 prop 键和id值匹配。例如:

const entities = {
  ghi: {
    id: 'aaaaa' // should throw an error as ghi doesn't match aaaaa
  }
}

有什么想法可以让我完成这项工作吗?

标签: typescript

解决方案


那是因为您定义idstringand'aaaaa'是一个字符串。你可以使用这样的东西,id它比以下步骤更具体string

type IdType = keyof typeof entities // "abc" | "def"

// and use it as id type

interface Entity {
  id: IdType
}

这可能不是您正在寻找的确切答案,但这是一个好的开始。希望它会有所帮助


推荐阅读