0

I have a business scenario which is equivalent to below tricky situation. Hence putting this problem across in a simple way as below.

File1.ts
import * from 'something';
export const var1="value of var1";

//lets say we have a variable 'x' and this needs to be exported too. However value of x is still unknown.
export const x;
File2.ts
import * from 'something';
//set the value of 'x' in File1.ts as 5
File3.ts
import * from 'something'
//I should be able to get the value of 'x' from File1.ts. But it should be equal to the value set by File2.ts which is 5

As mentioned above, I should be able to set the value of x from somewhere (in this case, File2.ts) and everytime I use 'x' from File1.ts, be it in File3.ts or any other file, the value of 'x' should be 5 (set from File2.ts)

Pavan Kumar
  • 129
  • 7
  • As the name says, you cannot reassign constants in TypeScript. However, you can declare global variables: https://stackoverflow.com/a/56984941/15770731 – Sebastian Salletmayer Sep 07 '22 at 09:03
  • Thank you @SebastianSalletmayer .issue with this approach is, say I define global variable 'x' in global.d.ts and I set value from file1.ts which means initially, 'x' value was undefined. say I have file2.ts with multiple functions. How can I use the global var 'x' on top of the .ts file before I define all the functions. say I use let value1=global.x at the beginning of file before all the functions, I get undefined for 'x' as this is derived during the initialization when app is loaded even before global variable 'x' is set. I wouldn't like to use let value1=global.x inside every function – Pavan Kumar Sep 07 '22 at 16:53

1 Answers1

1

File1.ts

var x = 99 //some unknow value

function setValueOfX(value){
  x = value
}

function getValueOfX(){
  return x
}

module.exports = {
  setValueOfX,
  getValueOfX,
}

File2.ts

const File1 = require('./File1.ts')

File1.setValueOfX(5) /// you can set the value of x using the function

File3.ts

const File1 = require('./File1.ts')

console.log(File1.getValueOfX()) /// you can get value of x by using .getValueOfX function