Use Of Trailing Commas In Typescript

Table of Content

What is typescript?

TypeScript is an open-source language that is built on top of JavaScript to provide build-time type checks.

TypeScript mimics syntax like statically typed language like Java and it helps to avoid runtime errors for JavaScript and detect the problem at build time.

Types in typescript provide you documentation plus build-time validation. The language is syntactic sugar and only present at the built time as typescript compiler code generates corresponding javascript code. So the types of typescript are not present at run time.

Example:

if you access some property or method which is not defined, JavaScript may not complain but typescript can help to detect it even before typescript code is converted to Javascript code.

What is a trailing comma and why does it matter in typescript?

Trailing commas (sometimes called “final commas”) is useful when adding new elements, parameters, or properties in JavaScript types like objects, arrays, functions parameters, and arguments, etc.

JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ECMAScript 5) and most recently (ECMAScript 2017) to function parameters.

As typescript is built on top of JavaScript it also allows trailing-commas as valid syntax.

Example:

The last entry in enum has a command which is an example of a trailing comma.

enum CountryName {
  INDIA,
  USA,
  SINGAPORE,
  CANADA,
  }

  const nums:number[] = [
  1,
  2,
  3,
  ]
 
interface Person {
   name:string;
   age:number;
  }

const person: Person =  {
 "name": "Nilesh Salpe",
  "age" : 30,
} as Person;

class Person {

  name(name:string, age:number,) :string {
      return "My " + name + "age is "+ age;

  }
}

What are the advantages of using trailing commas?

What are the disadvantages of using trailing commas?

References

Share this: