Closed sirisian closed 5 years ago
Ideally the spec would define that using var, let, or const with a type on the right of an assignment sets the variable type, but that would be a breaking change. It's possible to add a new operator, but that seems like overkill for such a minor thing. It would look like:
let foo := new MyType[5]();
foo = 5; // TypeError: foo is type MyType[5]
If this was implemented it would take over as a standard way to assign a type during declaration in a few cases where there's redundancy. So:
let foo = new MyType();
foo = 5; // foo is type 'any' and is 5
Would differ and the generally preferred usage would be:
let foo := new MyType();
foo = 5; // foo is type 'MyType' and an implicit cast is used if a constructor signature exists
Just to be clear I should include examples with const.
const a = new MyType(); // a is type MyType
const b:MyType = new MyType(); // Pointless
const c:MyType = 1; // Calls a matching constructor
const d:uint8 = 1;
In this case specifying the type with const can be redundant in some cases where type inference can be done.
Is this allowed below allowed?
class A {}
class B extends A {}
const e:A = new B();
In theory it could mean that one wishes to call the super functions on an instance of B. Analyzing this without having a modifier proposal like: https://github.com/sirisian/ecmascript-class-member-modifiers might be difficult.
Updated the spec to include typed assignment: https://github.com/sirisian/ecmascript-types#typed-assignment
There are probably edge cases I'm missing or more details I need to include. If anyone thinks of any I'd be interested to include them.
The last thing I want is for people to create multiple conventions thinking one is more right than others. The instance created of 5 elements of MyType is the same, but the variable itself is untyped, variable-length typed, and then fixed-length typed for the last example.
This section: https://github.com/sirisian/ecmascript-types#mixing-variable-length-and-fixed-length-arrays
I need to example the examples. Like is an array converted from fixed-length to variable-length. I need readable syntax that doesn't confuse users and is very clear when people make a choice on which to write.