Lab Style Guide: TypeScript

TypeScript Style Guide

For readability and maintainability, it’s critical to use a consistent coding style. The coding rules described in this document will help ensure that consistency.

Organization

Organize your computer code like you would a scientific paper.

  1. The largest unit of organization in a paper is the section (e.g., the “Results” section, the “Discussion” section, etc.).
    • In code, a “section” is comprised of all program elements that share the same general purpose (e.g., string manipulation, user input, etc.).
    • Each code section should be saved in a separate file. Organize your files in subdirectories to reflect the hierarchical organization of your code. In TypeScript, that means saving ts files to subdirectories and including them in your main script like this: /// <reference path='path/to/my_typescript.ts' />
  2. In a scientific paper, sections are divided into subsections.
    • In code, each class or function in a given file is equivalent to a subsection.
    • Typically there will be one class in each file, though in some cases multiple classes/functions per file may be appropriate.
  3. In scientific writing, subsections are divided into paragraphs.
    • In code, each of the functions within a class are like a paragraph.
    • Like a paragraph, the code in each function should be focused on a single task (like a topic sentence).
  4. Paragraphs are made of sentences.
    • In code, a “sentence” is a few commands that perform the same subtask.
    • It’s not necessary to comment every line, but it is best to include a brief comment at the beginning of each code “sentence.”

Here’s an example in meta code:

White Space

  1. Tabs aren’t allowed. Instead, use four spaces.
  2. Blank lines are useful for separating different code sections.
    • All code should end in a single blank line.
    • Two blank lines should precede every namespace, module, and class definition. Otherwise, two consecutive blank lines are not allowed.
  3. Spaces
    • Lines can’t end in spaces.
    • A space should follow every comma.
      1. Wrong: ("a","b")
      2. Right: ("a", "b")
    • Parentheses and square brackets aren’t padded with spaces.
      1. Wrong: ( "a", "b" ) [ "a", "b" ]
      2. Right: ("a", "b") ["a", "b"]
    • Certain characters must be flanked by spaces: + – < > =
      1. Wrong: 5+3=8 5>3-1 3<5
      2. Right: 5 + 3 = 8 5 > 3 - 1 3 < 5

Line Lengths

  1. No line can be longer than 79 characters.

Functions and Variables

  1. Function and variable names.
    • In TypeScript, functions are named using camelCase().
    • Classes, modules, and namespaces are named in TitleCase.
  2. All classes, namespaces, modules, and functions must have docstrings. Class, namespace, and module docstrings look like this:

Function docstrings look like this: