Home > Software engineering >  How to change value of global variable using function in typescript?
How to change value of global variable using function in typescript?

Time:10-30

I am trying to change the value of a global variable using a function.

Here is my js code:

var name="Samir";
var status=true;

function func1 () {
    status=false;
    name="sunny"
}


func1();

console.log(name);
console.log(status);

This works fine, but I was curious about how to implement the same functionality using typescript. Please guide me

CodePudding user response:

declare global {
   name: string;
   status: boolean;
}
function func1 () {
    globalThis.status = false;
    globalThis.name = "sunny"
}

CodePudding user response:

Your function is a poorly constructed example that works in JavaScript but not in valid in TypeScript.

Check the code here: TS Playground

The errors are

  1. Cannot redeclare block-scoped variable 'name'.'
  2. Subsequent variable declarations must have the same type. Variable 'status' must be of type 'string', but here has type 'boolean'.
  3. Type 'boolean' is not assignable to type 'string'.
  4. Cannot assign to 'name' because it is a constant.

Valid JS code will be,

let userName = "Samir";
let userStatus = true;

function func1 (userName, userStatus) {
    userStatus = userStatus;
    userName = userName;
}

func1("sunny", false);

console.log(userName);
console.log(userStatus);

Any valid JavaScript will pass through the TS compiler as TS is a superset of JS.

Make it type-safe by changing your function signature to

function func1 (userName: string, status: boolean)

CodePudding user response:

name and status are actually window properties. All you need to do is use different names and TS will not complain.

updated playground

  • Related