简体   繁体   English

使用 const 枚举键(不是值)作为接口属性

[英]Use const enum keys (not values) as interface properties

In following code variable x has properties a and z , but I want it to have a and b .在下面的代码变量x具有属性az ,但我希望它具有ab How can I express that in typescript?我如何用打字稿表达它?

const enum CE {
    a = "a",
    b = "z",
}

declare var x: Record<CE, any> // has 'a' and 'z'

Enum is variable itself, so you can query its type with typeof CE , then get its keys with keyof : Enum 本身就是变量,因此您可以使用typeof CE查询其类型,然后使用keyof获取其键:

declare var x: Record<keyof typeof CE, any> // Record<"a" | "b", any>

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM