在 Typescript 中导出常量并将其导入到另一个模块中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47307571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Export constant in Typescript and import it in another module
提问by Elias Garcia
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:
我开始尝试一些 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;
The VSCode is not recognizing the exported members and the compiler is giving me this error:
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'.
What am I doing wrong? Thanks.
我究竟做错了什么?谢谢。
PS: This is my tsconfig.json
file:
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"
]
}
采纳答案by Kirill Dmitrenko
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:
虽然错误消息有点误导,但它是有道理的。通过export const A = 'foo';
您导出变量,但type C = A;
尝试将其A
视为类型。而且没有一个。该示例可以进一步浓缩:
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
:
这将因“找不到 A 和 B”消息(类似于您的代码)而失败,因为A
andB
是variables,而不是types。要解决您的问题,您需要获取A
and类型B
:
type C = typeof A | typeof B;