简体   繁体   中英

Restrict type while updating value of variable in Javascript

I have one Javascript variable with assignment of number value to it like :

var myVar = 4;

function AlterVar ()
{
   // Here I am changing value of myVar with any thing 

   myVar = 'Changed It ';
}

AlterVar();

However, By doing it , now myVar is string. Is there any specific (Without manual coding) which restrict to assign anything other than number type to myVar ?

Thank you !!

There is no check for same type and assigning, but you could use a simple type check for same type.

 function alterVar (newValue){ if (typeof myVar === typeof newValue) { myVar = newValue; } } var myVar = 4; alterVar('Changed It '); console.log(myVar); alterVar(42); console.log(myVar); 

Javascript is a dynamically typed language. So, you cannot prevent this.

You can add checks to minimize the chances but when it comes to literals, you cannot guarantee.

You can prevent for objects though:

 var obj = {}; Object.defineProperty(obj, 'testKey', { set: function (value){ if(typeof value === 'string'){ this.value = value; } }, get: function(){ return this.value } }); console.log(obj) obj.testKey = '123'; console.log(obj) obj.testKey = { foo: '123' } console.log(obj) 

But if you are looking for completely statically typed language, you should look into Typescript.

Reference links:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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