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

喜欢而已 提交于 2019-12-01 02:05:24

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!