Why is the separator in a TypeScript TypeMemberList semicolon as opposed to comma?

This is a typescript interface:

interface A {
    l: { x: string; y:number }
}

But this (similar thing) produces an error:

interface A {
    l: { x: string, y:number }
}

// => Error: ';' expected.

On p.37 of the spec: http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

I see that indeed it is specified that a ; should appear there, but coming from JavaScript the semicolon in the middle of the object-literal-ish thing looks wrong.

Was this decision made to avoid ambiguity in the parser, or for some other reason?


Solution 1:

As of TypeScript 1.6 or so, you can now use either , or ; as a delimiter in interface declarations or anonymous object types! The team decided that the flexibility to use one or the other outweighed the concerns listed in the 'old answer' section.

You'll still need to use ; in class declarations to eliminate ambiguity:

x = 3;
class X {
  // Could be parsed as expression with comma operator,
  // or two declarations
  y = 1, x = 3;
}

I've retained the old answer below for historical context


Old answer

Technically it could have gone either way, but there are many strong reasons to use semicolons.

In programming languages, it's more common to see semicolons marking the ends of lines and commas separating things within a line (there are a few exceptions to this, like enums). Most TypeScript types are large enough that they span multiple lines, which makes semicolon a better choice.

There's also a desire to have interfaces and classes appear similar. Consider something like this:

interface Point {
    x: number;
    y: number;
}
class MyPoint {
    x: number;
    y: number;
}

It's much easier to make MyPoint implement Point via copy-and-paste, or change something from an interface to a class or vice versa, if they use the same delimiter. Arguably you could have made commas be the delimiting character in class declarations, but it's a hard sell to be the first programming language in common use to do that.

It's also desirable to be able to tell object literals and type literals apart at a glance. While the single-member { x: string } could be either depending on context, it's somewhat nicer if you can distinguish them based on their delimiter when the context isn't obvious in a complex expression.

Finally, every other language in common use with an interface syntax uses semicolons. When in doubt, follow convention, and the syntax for a type literal and an interface should definitely use the same delimiting character.