在Typescript中导出常量并将其导入另一个模块

时间:2017-11-15 12:33:46

标签: typescript

我开始尝试一些TypeScript功能,我想在一个模块中导出两个常量并导入它们并在另一个模块中使用它,如下所示:

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

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

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

VSCode无法识别导出的成员,编译器正在给我这个错误:

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'.

我做错了什么?感谢。

PS:这是我的tsconfig.json文件:

{
  "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 个答案:

答案 0 :(得分:4)

虽然错误信息有些误导,但它有一定道理。在export const A = 'foo';您导出变量,但type C = A;会尝试将A视为类型。而且没有一个。这个例子可以进一步浓缩:

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

type C = A | B;

由于“找不到A和B”消息(与您的代码类似),因为AB变量,而不是 types < / em>的。要解决您的问题,您需要获得AB的类型:

type C = typeof A | typeof B;