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"
]
}
To export a constant in TypeScript, we can use the export keyword. export const adminUser = { //... }; to export the adminUser constant.
To import a variable from another file in TypeScript: Export the variable from file A , e.g. export const str = 'hello world' . Import the variable in file B as import { str } from './another-file' .
Use named exports to export constants in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported constants can be imported by using a named import as import {A, B} from './another-file. js' . You can have as many named exports as necessary in a file.
The export declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the import declaration or dynamic import.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With