1

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.

3
  • Type inference and enum types make this possible. Use TypeScript-based autocompletion. Commented Apr 18, 2021 at 21:54
  • @Bergi, can you please elaborate? Commented Apr 18, 2021 at 22:12
  • 1
    Basically what @CertainPerformance wrote below. If you use an IDE that employs TypeScript for JS linting and autocompletion, it would work with the typeof example from your question out of the box. To define your own types and declare your variables, you'd need to use TypeScript proper though. Commented Apr 18, 2021 at 22:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.