exporting enum from typescript type definition file
Solved it by the help of Romain Denau's comment above. It nudged me in the right direction: What code does the typescript compiler generate from an enum (see https://www.typescriptlang.org/docs/handbook/enums.html#enums-at-runtime)? Declaring the enum const
allows the typescript compiler to completely swap the identifier with the respective value, effectively inlining it. No more leakage of the enum into the production code. Thanks!
//index.d.ts
export as namespace myLib;
export const enum MouseButton {
LEFT = 1,
MIDDLE = 2,
RIGHT = 4
}
export function activate(button : MouseButton ) : void;
From my short research on the topic, I noticed that exporting the enums from the type definition file using export enum const
is a bad idea. Since you have to enable the --isolatedModules
flag which isn't even possible in say create-react-app
and it can get messy.
Instead, I myself used the normal syntax in my shared.d.ts
file:
export enum EReviewStatus {
PENDING = 'PENDING',
SENT = 'SENT'
}
And then I have a .js
file, which is imported in the package.json
main-block eg:
"main": "shared.js",
Where I have (using CommonJS export to make it compatible in both Node.js and frontend):
module.exports.EReviewStatus = {
PENDING: 'PENDING',
SENT: 'SENT'
}
Which works and I think is better practise, as now your code is clearly separated from the types.
(To complete t.animal's own answer)
Declaration files are difficult to make: see the long documentation. Sometimes looking in existing .d.ts files can help.
Regarding enum
, declaring them as const enum
is a clean and simple approach. It's
what is done for jquery for instance, see @types/jquery/index.d.ts for Mouse
and Key
. It's handy because standard enums are compiled in JavaScript as arrays while const enum
members are compiled directly as values ; see TypeScript Playground.