TypeScript: an extension of an imported enumeration

I can combine enum declarations inside a single file, for example.

export enum Test { value1 = <any>'value1', value2 = <any>'value2' } export enum Test { value3 = <any>'value3' } 

This works great, but I intend to use a common jumper, which I can extend later, for example

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

I get

Individual declarations in the combined declaration "Test" must be all exported or all local.

Is there a way to achieve the desired behavior?

+5
source share
3 answers

In the https://github.com/Microsoft/TypeScript/pull/6213 section, you can:

 // 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 !;)

+6
source

After some research, I have to admit that I can't find a super-right way to do this.

But there are two possible solutions that are not so bad and not so stink.

User enumeration is performed first - this method does not allow consuming existing enumerations. This is probably the only limitation of this method. In addition, he looks simple and completely native.

Another way is to have a big hamcaund with [combining enumerations into one value with a separate type declaration. This method allows you to use existing, real transfers; however, it is less convenient to use because there are two objects that you should know: the enum value and the type of enumeration.

+1
source

I saw a way that you can add an additional method / method in an existing enumeration. this is by creating a function in a namespace similar to an enumeration 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 full information here https://basarat.gitbooks.io/typescript/docs/enums.html in the section "Enumeration with static functions"

+1
source

Source: https://habr.com/ru/post/1263592/


All Articles