Skip to content

TypeScript Style Guide

Grant Nestor edited this page Mar 9, 2018 · 4 revisions

Names

  1. Use PascalCase for type names and enum values.
  2. Use camelCase for function names, property names and local variables.
  3. Use UPPER_CASE for global constants.
  4. Use _ as a prefix for private properties and I as a prefix for interface names.
  5. Use whole words in names when possible.

Types

  1. Do not export types/functions unless you need to share them across multiple components.
  2. Within a file, type definitions should come first.

Comments

  1. Use JSDoc-style comments for functions, interfaces, enums, and classes.

Style

  1. Use arrow functions over anonymous function expressions.
  2. Always surround loop and conditional bodies with curly braces.
  3. Open curly braces always go on the same line as whatever necessitates them.
  4. else goes on the same line as the closing curly brace.
  5. Use two (2) spaces for indentation.
  6. Function and class signatures may exceed 80 chars; use a maximum of 80 chars for all other lines.
  7. Strings should always use single quotes if they do not contain interpolated values:
  let foo = 'bar';       // static string
  let baz = `${5 * 5}`;  // interpolated string
  let qux = 'These aren\'t the droids you\'re looking for.';  // escaped quotes in string

Classes

  1. Avoid public properties - use setters/getters.
  2. Do not use the public keyword for public members - it is implied by default.
  3. Initialize all private properties to an initial value or null, unless they will be initialized in the constructor. If a basic type is used, do not add a type specifier (e.g. private _someValue = 0;).
  4. Ordering of members within a class should be:
  • static
  • public
  • protected
  • private
  1. Start with getters/setters in each scope, then methods. Protected and private properties go last.
  2. Abstract methods go in the same location as they would in the implemented class.

Examples

  • Interface declaration:
/**
 * The base message object which can be sent to a message handler.
 */
export interface IMessage {
  /**
   * The type of the message.
   */
  type: string;
}
  • If-Else block:
if (parent) {
  this._parent = null;
} else if (this.isAttached) {
  this.detach(); 
}
  • Bit flags:
export enum WidgetFlag {
  /**
   * The widget is attached to the DOM.
   */
  IsAttached = 0x1,
}
export class Widget {
  /**
   * Test whether the given widget flag is set.
   */
  testFlag(flag: WidgetFlag): boolean {
    return (this._wflags & flag) !== 0;
  }

  /**
   * Set the given widget flag.
   */
  setFlag(flag: WidgetFlag): void {
    this._wflags |= flag;
  }

  /**
   * Clear the given widget flag.
   */
  clearFlag(flag: WidgetFlag): void {
    this._wflags &= ~flag;
  }

  private _wflags = 0;
}
Clone this wiki locally