【问题标题】:How to make Typescript enum with implements interfaces如何使用实现接口制作 Typescript 枚举
【发布时间】:2019-06-03 12:21:13
【问题描述】:

如何使用实现接口制作 Typescript 枚举

我当前有这 2 个枚举

所有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,
}

【问题讨论】:

    标签: javascript node.js typescript types enums


    【解决方案1】:

    您不能让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'.
    

    希望对您有所帮助。祝你好运!

    【讨论】:

      猜你喜欢
      • 2016-09-03
      • 2019-01-20
      • 2020-10-26
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      相关资源
      最近更新 更多