如何使用实现接口的方式创建 Typescript 枚举

3

如何使用实现接口的方式创建Typescript枚举

我目前有这两个枚举类型

所有 enum ENNAME 的键都应该只包含 enum POSTAG 的键

export enum POSTAG
{
    BAD = 0x80000000,
    D_A = 0x40000000,
    D_B = 0x20000000,
    D_C = 0x10000000,
}

export enum ENNAME
{
    D_A = 'a',
    D_B = 'b',
    D_C = 'c',
}

有没有办法做出类似这样的效果?
export interface ENNAME
{
    [k: keyof POSTAG]: string,
}
1个回答

4

你无法让枚举类型enum实现一个接口interface。但是,你可以设置一些编译时类型检查,以便在出错时发出警告,例如:

interface ENNAMEInterface extends Record<Exclude<keyof typeof POSTAG, "BAD">, string> { }
type VerifyExtends<T, U extends T> = true
type VerifyENNAME = VerifyExtends<ENNAMEInterface, typeof ENNAME>; // okay

如果值ENNAME与值POSTAG(减去"BAD")具有相同的键和字符串值,则应该编译。否则,VerifyENNAME将会给您一个错误:

export enum ENNAME {
  D_A = 'a',
  D_B = 'b',
  // oops, D_C is missing 
}

type VerifyENNAME = VerifyExtends<ENNAMEInterface, typeof ENNAME>; // error
//                                                 ~~~~~~~~~~~~~
//  Property 'D_C' is missing in type 'typeof ENNAME' but required in type 'ENNAMEInterface'.

希望这能帮到你。祝你好运!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接