TypeScript: extending imported enum

前端 未结 3 530
执念已碎
执念已碎 2020-12-31 07:17

I can merge enum declarations within a single file e.g.

export enum Test {
  value1 = \'value1\',
  value2 = \'value2\'
}

export enum          


        
相关标签:
3条回答
  • 2020-12-31 07:53

    I saw a way that you can add additional function/method in an existing enum. this is by create the function within a namespace similar to the enum type: Here

    enum Weekday {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }
    namespace Weekday {
        export function isBusinessDay(day: Weekday) {
            switch (day) {
                case Weekday.Saturday:
                case Weekday.Sunday:
                    return false;
                default:
                    return true;
            }
        }
    }
    
    const mon = Weekday.Monday;
    const sun = Weekday.Sunday;
    console.log(Weekday.isBusinessDay(mon)); // true
    console.log(Weekday.isBusinessDay(sun)); // false
    

    You can see the complete information here https://basarat.gitbooks.io/typescript/docs/enums.html at section "Enum with static functions"

    0 讨论(0)
  • 2020-12-31 07:57

    After some research I must admit I cannot find a super-proper way to do that.

    But there are two possible solutions that are not that bad and not stinking that much.

    First is implementing a custom enum - this way is not allowing to consume already existing enums. This is probably the only limitation of this method. Other than that it looks simple and quite native.

    Another way is a big hackaround with [merging enums into one value with a separate type declaration. This way allows to consume already existing, real enums; however it is less comfortable to use because there are two entities to be aware of: enum value and enum type.

    0 讨论(0)
  • 2020-12-31 08:16

    In refer to https://github.com/Microsoft/TypeScript/pull/6213 you can do :

    // test.enum.ts
    export enum Test {
      value1 = <any>'value1',
      value2 = <any>'value2'
    }
    
    // place-to-extend-enum.ts
    import { Test } from './test.enum';
    
    declare module './test.enum' {
      export enum Test {
        value3 = <any>'value3'
      }
    }
    

    ... Magic! ;)

    0 讨论(0)
提交回复
热议问题