sirisian / ecmascript-types

ECMAScript Optional Static Typing Proposal http://sirisian.github.io/ecmascript-types/
453 stars 4 forks source link

Replace syntax for typing arrays with generic syntax. #54

Closed sirisian closed 3 years ago

sirisian commented 3 years ago

Thinking out loud as usual:

A variable with an array type looks like this:

let a:[] = [0, 1, 2, 3];

I find this intuitive and compact.

It's reasonable to assume that generics would be added into JS in 10-20 years. An array with a generic type should to me intuitively use a generic syntax. Actionscript knew this as well as C# and many other languages. In AS3 it looked like:

var v:Vector.<String>;

The syntax currently in the proposal is:

let a:string[] = [0, 1, 2, 3];

Changing this we'd have:

let a:[]<string>;

I've mentioned before that I'd like to type the length of arrays to give developers as much control as possible. This would use the second parameter.

let a:[]<string, uint8>;

I can't say for sure that this has no edge cases in terms of the grammar. The biggest downside for me is that it requires two more characters, but I don't think that's a huge issue given that developers have been fine with this in other languages. (It's also still less characters than other languages that use List, Vector, etc keywords).

Just to be complete some more examples:

let a:[10]<uint8>;
let b:[3]<string, uint8> = ['foo', 'bar', 'baz'];
let c:[16, (x, y) => y * 4 + x]<uint8>;
c[1, 2] = 5;
sirisian commented 3 years ago

I updated the proposal with this syntax. Also if the nullable syntax is kept it seems to look better to do <uint8?> with the visual break than uint8?[].