如何在枚举接口中将枚举值用作键?

时间:2019-08-22 00:22:17

标签: typescript interface

我正在寻找一种使用枚举键来定义接口允许的键的方法,如何实现呢?

http://www.typescriptlang.org/play/index.html#code/KYOwrgtgBA4qAmwBOUDeAoKUIEMA2wUAvFAOS4GkA0mUAZsBYSaQ06egL7roCWIAF2R0cAY0IAFZAGcA9iDS0QOCMABcUaQKT8A5gG5auhMg1adIA1x6j5WqAAdgshwQ1SkckAG0AusShvWlQoZVUNUgBZHCQAT2ooYxBEJAi2fGBSKE4aLBCw9TIAKWQ4hKSUiPZs3LRQlULSItlMqkSTVLJq7l8efiEkEXEoKRcCGCRZMCd4ACFYuGTkRSwAelWoAAkAUQAlbY0AC1kAdygBWSgwaUIBQ8JQSHPLxGlRHQAjW-vAgGtgWL+ABu+DAhHuSGAAH5aN5-rENPDZHRzrEnMjYB1fO4ZPI-NZ0LYQPZ0a5gBMpjN5otKiNnGSKdNgHMFh0AhgsN4acgAHTpAjYxz0gi1JgaUkELhAA

enum Gender {
  male = 'male',
  female = 'female'
}

interface Person {
  name: string;
  gender: string;
}

const people: Person[] = [
  { name: 'Mary', gender: 'female' },
  { name: 'Jerry', gender: 'male' },
  { name: 'Joe', gender: 'male' }
]

interface PeopleGroupedByGender {
  // HERE: how to use the enum to describe the [key] value here?
  [key: keyof typeof Gender]: Person[]
}

const peopleGroupedByGender: PeopleGroupedByGender = {
  [Gender.female]: people,
  male: people
}

1 个答案:

答案 0 :(得分:1)

您收到错误消息:

  

索引签名参数类型不能为联合类型。考虑改用映射对象类型。

如消息所示,您可以使用mapped object type解决此问题:

c