TypeScript

TypeScript is a superset of JavaScript and is used to write code which is preprocessed into JavaScript at build time.

There is not yet an 'official' guide or convention but most rules used for your JavaScript code should extend to suitability for TypeScript as well.

The following advice is borrowed heavily from Basarat Al Syed

A formatter or linter for Typescript should be configured on your project, with rules committed to your project repository for consistent developer experience. The typescript-eslint tool is recommended but rome also lints and formats Typescript.

Interface

  • Use PascalCase for name. Don't prepend with I
  • Use camelCase for members

Type

  • Use PascalCase for name
  • Use camelCase for members

Namespace

  • Use PascalCase for names.

Enum

  • Use PascalCase for enum names
  • Use PascalCase for enum member

TypeScript enums can be problematic.

Null vs. Undefined

  • Prefer not to use either for explicit unavailability

Bad

let foo = { x: 123, y: undefined };

Good

let foo: { x: number; y?: number } = { x: 123 };
  • Use undefined in general (do consider returning an object like {valid:boolean, value?:Foo} instead)

Bad

return null;

Good

return undefined;
  • Use null where it's a part of the API or conventional

Reason: It is conventional in Node.js e.g. error is null for NodeBack style callbacks.

  • Use truthy check for objects being null or undefined

Formatting

IDEs should be used which allow typescript support and automatic formatting. It's also possible to use tsfmt on the command line.

  • Prefer single quotes
  • Use 2 space, not tabs
  • Use semicolons

Arrays

Annotate arrays as foos: Foo[] instead of foos: Array<Foo>

It's easier to read and is used by the TypeScript team.

type vs. interface

  • Use type when you might need a union or intersection.
  • Use interface when you want extends or implements
  • Otherwise, use what you prefer

Further Reading

The Google TypeScript Style Guide is a good source of best-practice with explanatory text on why and when conventions should be followed. typescript-eslint packages up a good set of recommended style conventions for TypeScript, steps to integrate the package with your project are included in the getting started guide. Some of the above rules are effectively enforced via the package, or by default integration of typescript linting in your IDE. Linting Typescript in WebStorm is covered by JetBrains, and in VS Code by Microsoft.