繁体   English   中英

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

[英]error TS2539: Cannot assign to 'c' because it is not a variable

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

我该如何解决?

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

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

从任何其他文件导入后

GlobalVars.c = 100;

看,这里有一个混乱。 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 之一
  • 将导入的值视为绑定(别名),而不是真正的标识符

使用对象作为命名空间:

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

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

export const options = {
    c: 10 as number
}

不能分配 c 变量,因为您使用了 let

export let c: any = 10;

你必须给喜欢

export c: any = 10;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM