-1

How do you lock a variable as to only accept int , string , bool ..etc? such as :

var test : int = 0;
var test2 : String = "test";

is it possible?

  • Not possible in JavaScript. You can look into [TypeScript](https://stackoverflow.com/questions/12694530/what-is-typescript-and-why-would-i-use-it-in-place-of-javascript) or other type enabling tools like [Flow](https://flow.org/) or [Tern.js](https://ternjs.net/). But they don't "lock" the value - they provide tooling to alert you if you assign `test = "hello"`. Also, no tool I know of allows you to check for *integers*. You can limit to *numbers*, however. – VLAZ May 13 '21 at 12:21

3 Answers3

1

Well, it is not possible to do with raw Node.js, because it is just a runtime for JavaScript. If you want to have strong types you should use TypeScript.

Here is useful reading for you on how to set up Node.js project with TypeScript https://blog.logrocket.com/typescript-with-node-js-and-express/

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Ayzrian
  • 2,279
  • 1
  • 7
  • 14
  • Oh okej, :/ it's a bit messy when creating a function given no instructions on what the params type is –  May 13 '21 at 12:34
0

You can't do it in Javascript, but you can do it in Typescript.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

JavaScript do no have types. Your can implement a "custom base class" to self verify values of yours properties, before set a value.

Other option is TypeScript: https://www.typescriptlang.org/