【问题标题】:error TS2539: Cannot assign to 'c' because it is not a variable错误 TS2539:无法分配给“c”,因为它不是变量
【发布时间】:2017-09-01 09:34:11
【问题描述】:

我有 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.

我该如何解决?

【问题讨论】:

标签: javascript typescript


【解决方案1】:

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

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

从任何其他文件导入后

GlobalVars.c = 100;

【讨论】:

  • 这似乎是一个比公认的答案更优雅的解决方案
  • 很棒的答案!谢谢
【解决方案2】:

看,这里有一个混乱。 Axel Rauschmayer 博士在this article 中指出了这一点:

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

所以你有两个选择:

  • 调整编译器选项,使您的模块被视为 CommonJS 之一
  • 将导入的值视为绑定(别名),而不是真正的标识符

【讨论】:

  • 感谢您的回答!如果我的理解是正确的,当它们是 bindings 时,c = 100 应该“将标识符 c 重新绑定到对象 100”,但 c 不是实际标识符。
【解决方案3】:

使用对象作为命名空间:

export let state = {
    c : 10 as number;
}

【讨论】:

    【解决方案4】:

    您当然可以只导出为内部带有c 变量的对象,例如:

    export const options = {
        c: 10 as number
    }
    

    【讨论】:

      【解决方案5】:

      无法分配 c 变量,因为您使用了 let

      export let c: any = 10;
      

      你必须给予喜欢

      export c: any = 10;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-01
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        • 2012-12-25
        • 2013-11-15
        相关资源
        最近更新 更多