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

前端 未结 1 1103
慢半拍i
慢半拍i 2020-12-14 13:46

This is a typescript interface:

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

But this (similar thing) produces an error:

         


        
相关标签:
1条回答
  • 2020-12-14 14:27

    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.

    0 讨论(0)
提交回复
热议问题