Skip to content
Search

CodingGuidelines:TypeScript

lastmod 2023-02-01created 2021-07-1112 edits

Spaces

Use 2 spaces. Not tabs.

Reason:

  • More JavaScript teams do this (e.g. airbnb, idiomatic, standard, npm, node, google/angular, facebook/react).
  • The TypeScript and VSCode teams use 4 spaces, but they are clearly the exception in the ecosystem.

Semicolons

Use semicolons.

Reason:

  • Explicit semicolons help language formatting tools give consistent results.
  • Missing ASI (automatic semicolon insertion) can trip up new developers. (e.g. foo() \n (function(){}))
  • TC39 also recommends it.

Array

Use Array<T> instead of [].

Reason:

  • It is easier to read.
  • The TypeScript team uses it.

Dictionary

Use Record<TK, TV>; instead of {}.

For reference, that Record turns out to be

type Record<K extends keyof any, T> = {
    [P in K]: T;
};

as shown above.

File names

Write file names in camelCase.

Reason:

  • Common in many JS teams.

Double quotes vs single quotes

The case for double quotes:

  • Consistency with Json

The case for single quotes:

  • Many companies use them (airbnb, standard, npm, node, google/angular, facebook/react)
  • Inline HTML is easier to express.
    • With single quotes it is const v = '<input type="text">';,
    • but with double quotes you need backslashes (\"), as in const v = "<input type=\"text\">";

So... my conclusion: use single quotes.

A few exceptions:

  • css's @charset "utf-8"; is part of the spec, so it is required.
  • json files are an exception because of the spec.

See also

Favorite site

author Zer0 sitemap