Search code examples
typescriptsyntax

In a type alias for an object type are the properties separated by semicolon (;) or by comma (,)?


I just started learning TypeScript, so I have a question about syntax.

In a type alias for an object type are the properties separated by semicolon (;) or by comma (,)?

I see from The TypeScript Handbook, that ; is used.

// object literal type
type Person = {
  name: string;
  age: number;
};

However, in other code samples on the web, for example w3schools, I see comma (,).

type CarYear = number
type CarType = string
type CarModel = string
type Car = {
  year: CarYear,
  type: CarType,
  model: CarModel
}

I thought this code with the comma was wrong, but it seems to transpile fine into JavaScript.

By the way, in these similar-looking, but actually different cases, a comma is correct.

// inferred type from setting to an object literal
const car = {
  year: 2009,
  type: "Toyota"
};

// defining an object while using a type alias.
const car: Car = {
  year: 2009,
  type: "Toyota"
};

// tuple type
type Data = [
  location: Location,
  timestamp: string
];

But back to the main question: For separating the properties in a type alias for an object type, is comma(,) just wrong? Or also acceptable? And why?


Solution

  • Formatters by default will go toward the use of the semicolon:

    type CarYear = number;
    type CarType = string;
    type CarModel = string;
    type Car = {
      year: CarYear;
      type: CarType;
      model: CarModel;
    };
    
    type Person = {
      name: string;
      age: number;
    };