Type annotations inside destructuring
It seems like the following should be supported:
var [a: String, b: Number] = ["foo", 1];
function foo([a: String, b: Number]) {}
foo(["foo", 1]);
Is this a deliberate decision or was the scope of ES6 type annotations restricted until ES6 became more widespread?
Thanks!
We've held off on adding inline type annotation for destructuring since there isn't an obvious place in the grammar for object destructuring (var {a: string, b: number} = x will bind x.a to string and x.b to number). Array destructuring doesn't have this problem, so we could definitely add it.
Also I don't think TypeScript supports these kinds of annotations, so it wasn't something we urgently needed to support. You're saying the 6to5 acorn fork has support?
@gabelevi Yeah, I was rewriting some of the flow parsing in acorn-6to5 and accidentally added it in. Only my examples with array destructuring work correctly because as you said, syntax ambiguity.
Hmm, interesting how TypeScript / Flow are going to resolve this. Ideally, we could just do it during scope analyzing so if "property value" of object pattern is linked to type, then use it as type annotation and if not, use as destructuring target.
The only downside will be for cases like:
class A {}
var {a: A} = obj;
when you really want to override locally defined class and reassign A = obj.a, but I don't think this is an often case and it can be easily workarounded on developer side.
@RReverser You can just do:
class A {}
var { a }: { a: A } = obj;
@sebmck That doesn't look good enough - variables and their types are split into different sides of operator. It works for regular object literals, but doesn't look so nice for bindings.
I've been thinking about this for awhile, and I think the : type paradigm just isn't going to fit into the grammar for object literals, patterns and types. I think if we're going to add inline type annotations then we need to switch paradigms. I've been thinking maybe we could do something like
// Works well for object types
var { number x; string y } = { x: 123, y: "hello" };
// Works well for object patterns
function foo({number a, string b}) {}
// Not so sure if object literals need this
var z = {
?string m: null,
?number n: null
};
// because soon Basil's new expression annotation syntax will land
// which will help object literals
var z2 = {
m: (null: ?string),
n: (null: ?number)
}
The downsides include that this paradigm doesn't match the other type annotations and that there are certain reserved keywords in the modifier position (get, set, static).
@gabelevi, maybe I am being dense here, but why is var {a: string, b: number} = x not possible? Shouldn't the context be enough to disambiguate between destructuring-with-type-annotations and object literal syntax?
Oh, nevermind. I forgot about rebinding destructuring.
TypeScript uses as as a coercion operator. How about the following?
var { x as number, y as string } = { x: 123, y: "hello" };
function foo({a as number, b as string}) {}
var z = {
?m: null as string,
?n: null as number,
};
Alternatively, one could also use “Basil's new expression annotation syntax” everywhere:
var { (x : number), (y : string) } = { x: 123, y: "hello" };
function foo({ (a : number), (b : string)}) {}
var z = {
m: (null : ?string),
n: (null : ?number)
}
But I like as, because then there is no overloading of the single colon (and less parens). A double colon (instead of as) would also be nice, but IIRC that is reserved by TC39 for guards.
Hmm, I actually like { (x : number) } = { x: 123 }. Seems totally unambiguous and unlikely to conflict with future ECMA-262 proposals. Any objections? /cc @gabelevi
:+1: to @rauschma's idea of using "as".
:+1: to @rauschma's other idea of using "expression annotation syntax", or what I naïvely call "casting".
This would be super useful for functional React components:
const Component = ({
propA,
propB,
}) =>
....
Currently, the best way is to create a type and access the props via field access (that way only prop. is repeated a lot, but not the names of the props).
type Props = {
propA: SomeType,
propB: SomeType,
}
const Component = (props: Props) =>
....
Clearly the destructuring and typing syntaxes clash :(. This makes sense to me, but is super ugly:
const Component = ({...}: {
propA: SomeType,
propB: SomeType,
}) =>
(since empty {} destructuring seems to be going through the committee, and wouldn't be obvious anyway). This is probably currently illegal, but I have no reasoning for it:
const Component = ({{
propA: SomeType,
propB: SomeType,
}}) =>
What I'm looking for is a solution that lets us easily go from typed params to named typed params:
f = (a: X, b: Y) => ...
f = ({{a: X, b: Y}}) => ...
What about this? I like "as" operator too - it is short, simple and evident. This example is good:
function foo({ a as number, b as string }) {}
Just bumped into this myself. I also support { (x : number) } = { x: 123 } since it aligns with type annotations elsewhere. I don't think we need to add a new keyword.
For some reason I thought { x: (localX: number) } = { x: 123 } would work, but perhaps it also should work.
This syntax is confuzy - too easy to make mistake.
I was on a long plane ride this weekend so I figured I'd toy around with the paren-grouping syntax (i.e. let { (x:number) } = {x:123}) because it's simple, it composes well with the rest of of our lval type annotations, and when paired with object literals it unlocks the ability to type a property slot (rather than having to type the value and inferring the property slot from that). On objects, this would unlock the ability to understand deferred initialization of a property similar to how we can with let/var (i.e. let foo:number; foo = 42; --> let a = { (someNum:number) }; a.someNum = 42;)
On syntax: I went with what matches the most with our other annotation positions. TBH I don't find the syntax beautiful, but I don't think we're going to find something that everyone agrees on there. Additionally, after playing a bit I don't find it prohibitively inexcusable.
My branch is linked below. It doesn't wire up enforcement of the destructuring annotations just yet -- but it shows that we can if we wanted to pursue this route:
https://github.com/jeffmo/flow/tree/pattern_lval_annotations
Did you get in contact with the TypeScript team? Ideally, a syntactic solution would be adopted by both Flow and TypeScript.
@rauschma: I haven't on this, no (this was just plane-ride hackery) -- I'm happy to reach out.
EDIT: I guess this isn't really casting, so maybe casting syntax consistency doesn't matter too much
@jeffmo It's not about casting consistency, but rather would be nice to have as much syntax shared as possible. I'm pretty sure they were also exploring options for typing destructuring, so collaboration could help in both short-term and long-term perspectives.