Search code examples
typescriptplunker

Does TypeScript allow object literals without commas between properties?


I was looking at the documentation for ng-bootstrap and noticed that one of their examples leaves out a comma in an object-literal definition. (I can't link directly to the files in a Plunker, but it's line 30 of src/app.ts.)

@NgModule({
  imports: [BrowserModule, FormsModule, ReactiveFormsModule, JsonpModule, NgbModule.forRoot()], 
  declarations: [App, NgbdDropdownManual]
  bootstrap: [App]
}) 
export class AppModule {}

This led me to play around with the Plunker, and it turns out you can remove all the commas in the object declarations and the code still compiles and runs -- try adding console.log({a:1 b:2}) to see what I mean.

Is this formally supported in all TypeScript, or is it an artifact of the way the code is compiled and run in this specific example?


Solution

  • It's most likely a result of the fact that when transpiling tsc will insert missing punctuation marks.

    for example

    let x = {
      a: 2 b: 4
    }
    

    gets compiled to:

    var x = {
       a: 2, b: 4
    };
    

    At the same time a compilation warning is issued telling you that , is expected.

    While this seems to be working I wouldn't rely on it since it seems to be nothing more than unintended consequence.

    You can see this example in the playground here.