Reply
You're right!! The type is inferred by the compiler at the initialisation of the identifier, saving the developer from manually asserting the type.
A value assigned to a variable must evaluate to be a primitive(that's how the typeof operator works!!)
Promise is an instanceof Object, here object is the primitive type(i.e, typeof Promise === "object" ), therefore the variable can only hold objects.
Eg:-
let <regex> = new RegExp("(she|he)llo");
//regex is reserved for objects but not specifically for the instance RegExp.
regex = {} //perfectly valid
If preferred by the language developers, variable preserved for specific object instances can also be implemented.
My suggestion:
let <regex instanceof RegExp> = new RegExp("(she|he)llo");
//or
let <regex in RegExp> = new RegExp("(she|he)llo");
//or
let <regex of RegExp> = new RegExp("(she|he)llo");
regex = {}; //Error
Variables with object instance preservation can be done likewise by giving a new meaning to any of the membership operators mentioned above within the angle brackets.
-
instanceof is much more readable.
-
in is much more concise.
-
of can also be considered.
However, my initial suggestion is to implement the variable preservation for primitive types only.
The object instance preservation can be set aside for later consideration.
The reason I say this is because:
let <greet in String>;
greet = "hello";
Does this behavior be endorsed??
- We should decide whether greet can only hold an object of instance String or a primitive string.
- what will happen if:
let <greet String>;
console.log(greet);//undefined or ""
These decisions along with others should be considered only after rigorous discussions.
The discussion on implementation details is the concern of language implementers. Not the scope of my concern.
This however is an experimental syntax and should be treated as such. Therefore, the syntax should't be taken into account for the evaluation. The idea of variable preservation should be the focus.
A valid concern that I raise is that the current syntax might cause some problems with compiler like Babel, Harp, or Svelte, because they use the angle brackets extensively(like in JSX). Therefore the syntax shouldn't be considered.
In my proposal, type preservation of identifiers works in relation to the typeof operator(which of course has some pitfalls). @Ijharb, your suggestion is that it should also take instancing of objects in consideration(relating the instanceof operator). As I said earlier, the details should be dealt with the language implementers(i.e, if this feature is ever introduced to the language).
Conclusion
This idea has never been introduced to any other language. If JavaScript implements this feature, it will be the first to introduce a revolutionary way of type setting identifiers, and also it will prove to the world that an eighteen year old can make a difference...