您可以通过使用枚举键创建对象来做其他方式:
enum SomethingKeys {
red = "red",
blue= "blue",
green= "green",
}
type ISomething= Record<SomethingKeys, string>
const a: ISomething = {
[SomethingKeys.blue]: 'blue',
[SomethingKeys.red]: 'red',
[SomethingKeys.green]: 'green',
}
但我认为您真正需要的不是枚举,而是联合类型的键,您由keyof 定义。考虑:
interface ISomething {
red: string;
blue: string;
green: string;
}
type Keys = keyof ISomething; // "red" | "blue" | "green"
当您声明自己是新手时,可以使用字符串文字联合。你不需要枚举。
当您拥有Keys 时,您也可以使用它们来创建其他类型
// new object with keys of the original one
type OtherTypeWithTheSameKeys = Record<Keys, number> // type with keys of type Keys
const a: OtherTypeWithTheSameKeys = {
blue: 1,
green: 2,
red: 3
}