【问题标题】:Export constant in Typescript and import it in another module在 Typescript 中导出常量并将其导入另一个模块
【发布时间】:2018-04-28 16:30:20
【问题描述】:

我开始尝试一些 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"
  ]
}

【问题讨论】:

  • 您使用什么编译器设置?你有可以给我们看的tsconfig.json吗?
  • 我已经用 tsconfig.json 文件内容@TomFenech 更新了我的答案

标签: typescript


【解决方案1】:

虽然错误消息有些误导,但还是有一定道理的。通过export const A = 'foo';,您正在导出一个变量,但type C = A; 试图将A 视为一个类型。而且没有。这个例子可以进一步精简:

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

type C = A | B;

这将失败并显示“找不到 A 和 B”消息(类似于您的代码),因为 AB变量,而不是类型。要解决您的问题,您需要获取AB 的类型:

type C = typeof A | typeof B;

【讨论】:

  • 是的...你完全正确!我试图做的就像说:I want the type C to be 'foo' or 'bar' 但不使用简单的字符串。这可能吗?
  • 是的,答案中的最后一个代码 sn-p 正是这样做的(假设您有 A: 'foo'B: 'bar',例如,作为在第一个 sn-p 中声明的常量)。对于你的例子,你可以写type IState = typeof ThemeNameEnum.CAMPUS | typeof ThemeNameEnum.TOKIO;
  • 嗯,好吧!例如,我认为typeof ThemeNameEnum.CAMPUS 将返回string。谢谢你的解释!
  • 例如,如果我们使用let 而不是const 或明确输入为string(即const A: string = 'foo')。但是由于我们将常量的类型留给编译器来推断,它试图提出最窄的可能类型(即“最精确”的类型)。由于声明为 const 的字符串无法更改(与例如数字相同),因此最窄的类型是与 const 变量的值相同的字符串文字类型。
  • 是的,请注意,类型声明中的 typeof 与 JS 中的 typeof 运算符不同。
猜你喜欢
  • 1970-01-01
  • 2021-04-16
  • 2023-01-10
  • 2022-01-08
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
相关资源
最近更新 更多