Wassim Tahraoui
Wassim Tahraoui

Reputation: 179

Limiting values to a variable in Node.js

I'm not sure if this question makes sense but when I'm using an IDE and for example I type:

x = 5
s = typeof(x)
if (s === ) //Cursor selection after === (before i finished the statement)

the IDE's autocomplete feature gives me a list of the possible values. And if I type value that doesn't exist in that list it's highlighted, and when I execute the program (in other examples, not this one), it throws an error.
I want to achieve a similar functionality with my own variables so that I can only assign specific values to it.

Upvotes: 1

Views: 299

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

I'd recommend using TypeScript. See this question.

For example, your code will throw a TypeScript error if you try to compare the result of typeof against anything that isn't a proper JavaScript type:

x = 5
s = typeof(x)
if (s === 'foobar') {
}

results in

enter image description here

In a reasonable IDE with TypeScript (such as VSCode), any line of code that doesn't make sense from a type perspective will be highlighted with the error.

If you want to permit only particular values for some variable, you can use | to alternate, eg:

let someString: 'someString' | 'someOtherString' = 'someString';

will mean that only those two strings can occur when doing

someString = 

later.

TypeScript makes writing large applications so much easier. It does take some time to get used to, but it's well worth it IMO. It turns many hard-to-debug runtime errors into (usually) trivially-fixable compile-time errors.

Upvotes: 2

Related Questions