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

xie*_*ing 10 javascript typescript

我有2个.ts文件,

C.ts:

export let c: any = 10;
Run Code Online (Sandbox Code Playgroud)

A.ts:

import { c } from "./C";
c = 100;
Run Code Online (Sandbox Code Playgroud)

当我编译A.ts时,出现错误:

error TS2539: Cannot assign to 'c' because it is not a variable.
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

rai*_*7ow 22

看,这里有一个混乱。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
Run Code Online (Sandbox Code Playgroud)

所以你有两个选择:

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


Moh*_*lim 12

将其放置在类中,并使其静态

export class GlobalVars {
  public static c: any = 10;
}
Run Code Online (Sandbox Code Playgroud)

从任何其他文件导入后

GlobalVars.c = 100;
Run Code Online (Sandbox Code Playgroud)

  • 这似乎是一个比接受的答案更优雅的解决方案 (2认同)
  • 很棒的答案!谢谢 (2认同)