打字稿:接口键枚举

时间:2020-01-23 15:03:38

标签: typescript enums interface

我有一个界面:

public class EAccessAuthenticationFilter extends RequestHeaderAuthenticationFilter {
    public EAccessAuthenticationFilter() {
        super(new RequestMatcher() {
                        RequestMatcher matcher = new AntPathRequestMatcher("/v1/api1");
            return matcher.matches(request);    

        });
    }
}

是否可以定义表示接口键的枚举?

我想要这样的结果:

interface ISomething {
  red: string;
  blue: string;
  green: string;
}

ps:我是ts的新手,如果问题不正确,对不起。

1 个答案:

答案 0 :(得分:2)

您可以通过创建带有枚举键的对象来做其他事情:

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
}