Export constant in Typescript and import it in another module

Viewed 27325

I'm starting to try some TypeScript features and I want to export two constants in one module and import them and use it in another module like this:

// module1.ts
export const CAMPUS = 'campus';
export const TOKIO = 'tokio';

// module2.ts
import * as ThemeNameEnum from './module1';

export type IState = ThemeNameEnum.CAMPUS | ThemeNameEnum.TOKIO;

The VSCode is not recognizing the exported members and the compiler is giving me this error:

ERROR in /Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-reducer.ts (4,36): Namespace '"/Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-name-enum"' has no exported member 'CAMPUS'.
ERROR in /Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-reducer.ts (4,59): Namespace '"/Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-name-enum"' has no exported member 'TOKIO'.

What am I doing wrong? Thanks.

PS: This is my tsconfig.json file:

{
  "compilerOptions": {
    "baseUrl": "",
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
    "dom",
      "es2017"
    ],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "removeComments": true,
    "outDir": "../dist/client",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "../node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}
1 Answers

Whereas the error message is somewhat misleading, it makes some sense. By export const A = 'foo'; you're exporting a variable, but type C = A; tries to treat A as a type. And there isn't one. The example can be condensed further:

const A = 'foo';
const B = 'bar';

type C = A | B;

That will fail with "cannot find A and B" message (similarly to your code), because A and B are variables, not types. To solve your problem you need to get type of A and B:

type C = typeof A | typeof B;
Related