Typescript —确保对象的prop键与prop值相同

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

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

Each object prop key needs to match its corresponding id.

我尝试这样做:

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

interface Entity {
  id: string;
}

But this does not ensure that the prop key and id value match. For example:

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

有什么想法可以使我工作吗?

评论