cleancode.in

Clean code in TypeScript

The TypeScript handbook’s Do’s and Don’ts are about types: number, string and boolean, never Number, String or Boolean; no any; unions and optional parameters over overloads; void for an ignored callback value.

What does the TypeScript handbook ask for?

  • Don’t ever use the types Number, String, Boolean, Symbol, or Object source

From TypeScript handbook, Do’s and Don’ts. For names, see the JavaScript page.

What else does it ask?

  • The primitive types number, string, boolean, symbol. source
  • No any, except while moving a JavaScript project over. source
  • Union types over overloads. source
  • Optional parameters over extra overloads. source
  • void for callbacks whose value is ignored. source

What does cleaner TypeScript look like?

Before
function label(value: any): String {
  return "Item " + value;
}

function onSave(callback: (id: number) => any) {
  callback(42);
}
After
function label(value: number | string): string {
  return `Item ${value}`;
}

function onSave(callback: (id: number) => void): void {
  callback(42);
}

What changed?

  • string, the primitive type, in place of String, the wrapper object. source
  • A union of the two types label really takes, in place of any. source
  • The callback’s value is never used, so its type says void. source