Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have 2 .ts files,

C.ts:

export let c: any = 10;

A.ts:

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

When I compile A.ts, a error:

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

How can I fix it?

like image 887
xieyuesanxing Avatar asked Sep 01 '17 09:09

xieyuesanxing


3 Answers

place it inside a class, and make it static

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

after importing it from any other file

GlobalVars.c = 100;
like image 92
Mohamed Ali Avatar answered Nov 18 '22 22:11

Mohamed Ali


See, there's a confusion here. And Dr. Axel Rauschmayer nailed it in this article:

CommonJS modules export values. ES6 modules export bindings - live connections to values.

//------ 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

So you have two options:

  • adjust the compilerOptions so that your module is treated as CommonJS one
  • treat the imported values as bindings (aliases), not true identifiers
like image 22
raina77ow Avatar answered Nov 18 '22 22:11

raina77ow


Use objects as namespaces:

export let state = {
    c : 10 as number;
}
like image 4
Mahmoud K. Avatar answered Nov 18 '22 22:11

Mahmoud K.