错误 TS2539:无法分配给“c”,因为它不是变量

新手上路,请多包涵

我有 2 个 .ts 文件,

C.ts:

 export let c: any = 10;

A.ts:

 import { c } from "./C";
c = 100;

当我编译A.ts时,报错:

 error TS2539: Cannot assign to 'c' because it is not a variable.

我该如何解决?

原文由 xieyuesanxing 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 594
2 个回答

看,这里有一个混乱。 Axel Rauschmayer 博士在 这篇文章 中强调了这一点:

CommonJS 模块导出值。 ES6 模块导出绑定——与值的实时连接。

 //------ lib.js ------
export let mutableValue = 3;
export function incMutableValue() {
    mutableValue++;
}

//------ main1.js ------
import { mutableValue, incMutableValue } from './lib';

// The imported value is live
console.log(mutableValue); // 3
incMutableValue();
console.log(mutableValue); // 4

// The imported value can’t be changed
mutableValue++; // TypeError


所以你有两个选择:

  • 调整 compilerOptions 以便您的模块被视为 CommonJS 一个
  • 将导入的值视为绑定(别名),而不是真正的标识符

原文由 raina77ow 发布,翻译遵循 CC BY-SA 3.0 许可协议

将它放在一个类中,并使其成为静态的

export class GlobalVars {
  public static c: any = 10;
}

从任何其他文件导入后

GlobalVars.c = 100;

原文由 Mohamed Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题