Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-export enum in typescript

Tags:

typescript

I have an enum declared somewhere in a sub module, and I'd like to re-export it in my actual project.

module :

export enum name {
  TOTO = "toto",
  TITI = "titi",
}

export :

import { name } from "module"
export type name2 = name

index.ts:

switch (var) {
  case name2.toto: // 'name2' only refers to a type, but is being used as a value here.
}

How can I not lose information that name2 is initially an enum ?

like image 811
mmeisson Avatar asked Jan 27 '23 12:01

mmeisson


2 Answers

Your re-export should be:

export { name as name2 };

This can be used with any kind of declared name: variable, enum, class, etc.

like image 154
Matt McCutchen Avatar answered Jan 30 '23 02:01

Matt McCutchen


The suggested method didn't work for me, as I import names like this:

import * as API from './__generated__/api/data-contracts.ts' 

In such circumstances, one doesn't simply export it as:

export { API.name as name2 };

because it's an error.

Luckily, I've finally learned a way to do it, thanks to [email protected]#javascript:

export type name2 = API.name;
export const name2 = API.name;

This way, we get the best of both worlds - types and values. And TS will figure out which one it wants.

like image 44
Onkeltem Avatar answered Jan 30 '23 02:01

Onkeltem