re-export Typescript enum from namespace?
Asked Answered
C

2

12

I have an enum definition in module 'some-lib'. I want to re-export it from a namespace in my module, something like this:

import { PaymentType } from 'some-lib';

namespace Payout {
    export enum PaymentType = PaymentType;
}

I'm not having any luck. I want to do this in order to alias the enum and put it into a different namespace to avoid collisions with other types with the same name. I don't want to have to define a duplicate copy of the enum in my code, and have to maintain all the enum values.

Is there any way Typescript supports this currently?

Corroboration answered 7/12, 2017 at 18:11 Comment(0)
C
34

Yes, there's a way to do this, e.g.:

import { PaymentType as _PaymentType } from 'some-lib';


namespace Payout {
  export import PaymentType = _PaymentType;
}

or alternatively:

import * as SomeLibTypes from 'some-lib';


namespace Payout {
  export import PaymentType = SomeLibTypes.PaymentType;
}

reference: https://github.com/Microsoft/TypeScript/issues/20273#issuecomment-347079963

Corroboration answered 7/12, 2017 at 18:24 Comment(2)
Outstanding! So simple, but I never would have figured out the proper syntax. Thanks!Untrue
I get the following error: import =` is not supported by @babel/plugin-transform-typescript Please consider using import <moduleName> from '<moduleName>'; alongside Typescript's --allowSyntheticDefaultImports option.Backwater
M
0

You could make it a little simpler with explicit enum rename at re-export time as usually needed if your code is going to be an npm package.

import { PaymentType } from 'some-module.js';

export namespace Payout {
    export import Type = PaymentType ;
}

Now you import and use it as

import { Payout } from 'my-distributed-package'

const type = Payout.Type.Actual-enum-defined
Monologue answered 27/5 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.