我很想知道是否可以将enum用作接口中的对象键。 我为它做了一点测试:
export enum colorsEnum{
red,blue,green
}
export interface colorsInterface{
[colorsEnum.red]:boolean,
[colorsEnum.blue]:boolean,
[colorsEnum.green]:boolean
}
当我运行它时,我收到以下错误:
A computed property name in an interface must directly refer to a built-in symbol.
我做错了还是不可能?
答案 0 :(得分:13)
好的,关键思想是将Enum转换为正确的Type并使用它扩展Interface: You can check it out in live code here.
const enum Enum {
key1 = "value1",
key2 = "value2",
key3 = "value3",
}
type EnumKeys = keyof typeof Enum;
type EnumKeyFields = {[key in EnumKeys]:boolean}
interface IEnumExtended extends EnumKeyFields {
KeyEx1:boolean;
KeyEx2:string;
}
// Test it
const enumInstance: IEnumExtended = {
};
当您进入enumInstance
时,将获得Enum键而不是值的自动完成功能。
答案 1 :(得分:6)
要定义接口,必须提供不计算的成员名称。
export interface colorsInterface {
red: boolean;
blue: boolean;
green: boolean;
}
如果您担心保持枚举和界面同步,可以使用以下内容:
export interface colorsInterface {
[color: number]: boolean;
}
var example: colorsInterface = {};
example[colorsEnum.red] = true;
example[colorsEnum.blue] = false;
example[colorsEnum.green] = true;
TypeScript非常高兴您将枚举作为索引传递,如果您决定重命名red
,则重命名重构会将所有内容保持在一起。
答案 2 :(得分:2)
您可以尝试输入:
export enum colorsEnum{
red, blue, green
}
export type colorsInterface = {
[key in colorsEnum]: boolean;
};
let example: colorsInterface = {
[colorsEnum.red]: true,
[colorsEnum.blue]: false,
[colorsEnum.green]: true
};
或者,如果您不想使用所有键,请添加一个?
export type colorsInterface = {
[key in colorsEnum]?: boolean;
};
let example: colorsInterface = {
[colorsEnum.red]: true,
[colorsEnum.blue]: false
};
答案 3 :(得分:2)
为什么不让它尽可能简单:
export enum Color {
Red = 'red',
Blue = 'blue',
Green = 'green'
}
export interface IColors{
[Color.Red]: boolean,
[Color.Blue]: boolean,
[Color.Green]: boolean
}
答案 4 :(得分:1)
这对我们有用:
type DictionaryFromEnum = {
[key in keyof typeof SomeEnum]?: string
}
答案 5 :(得分:0)
使用原生 Record<Keys, Type>
实用程序的简单解决方案。 (Docs)
export enum Colors {
RED = 'red',
GREEN = 'green',
BLUE = 'blue'
}
export type ColorInterface = Record<Colors, boolean>
这种类型转换为:
// translates to:
export type ColorInterface = {
red: boolean;
green: boolean;
blue: boolean;
}
重要:您必须定义一个 enum
键并将值相应地映射到它们,否则,您将获得一个使用枚举的 index
如下所示:
export enum Colors {
'red',
'green',
'blue'
}
export type ColorInterface = Record<Colors, boolean>
// translates to:
export type ColorInterface = {
0: boolean;
1: boolean;
2: boolean;
}
或者,如果您不想显式定义枚举键,或者如果您只有几个键可以使用,您也可以使用 type
别名定义颜色,这也将正确转换为您需要的:
export type Colors = 'red' | 'green' | 'blue'
// will also translate to:
export type ColorInterface = {
red: boolean;
green: boolean;
blue: boolean;
}