在枚举中使用枚举作为界面键 [英] Using enum as interface key in typescript

查看:178
本文介绍了在枚举中使用枚举作为界面键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否可以使用枚举作为接口中的对象键
我已经为此建立了一个小小的测试:

  export enum colorsEnum {
red,blue,green
}

export interface colorsInterface {
[colorsEnum.red]:boolean,
[colorsEnum.blue]:boolean,
[colorsEnum.green]:boolean
}

当我运行它时,我收到以下错误:

 界面中的计算属性名称必须直接指代内置符号。 

我做错了,还是不可能?

解决方案

要定义界面,必须提供成员名称不计算。

  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;
示例[colorsEnum.green] = true;

TypeScript非常高兴为您传递枚举作为索引,然后重命名重构将保留如果您决定重新命名 red ,那么所有的一切。


I was wonder if I can use enum as an object key in interfaces.. I've built a little test for it:

export enum colorsEnum{
red,blue,green
}

export interface colorsInterface{
[colorsEnum.red]:boolean,
[colorsEnum.blue]:boolean,
[colorsEnum.green]:boolean
}

When I run it I'm getting the following error:

A computed property name in an interface must directly refer to a built-in symbol.

I'm doing it wrong or it just not possible?

解决方案

To define an interface, the member names must be supplied not computed.

export interface colorsInterface {
    red: boolean;
    blue: boolean;
    green: boolean;
}

If you are worried about keeping the enum and the interface in sync you could use the following:

export interface colorsInterface {
    [color: number]: boolean;
}

var example: colorsInterface = {};
example[colorsEnum.red] = true;
example[colorsEnum.blue] = false;
example[colorsEnum.green] = true;

TypeScript is perfectly happy for you to pass the enum as the index and a rename-refactor would then keep everything together if you decided to rename red, for example.

这篇关于在枚举中使用枚举作为界面键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆