Skip to content

Latest commit

 

History

History
121 lines (84 loc) · 4.2 KB

which-ts.md

File metadata and controls

121 lines (84 loc) · 4.2 KB

Item 2: Know Which TypeScript Options You're Using

Things to Remember

  • The TypeScript compiler includes several settings that affect core aspects of the language.
  • Configure TypeScript using tsconfig.json rather than command-line options.
  • Turn on noImplicitAny unless you are transitioning a JavaScript project to TypeScript.
  • Use strictNullChecks to prevent "undefined is not an object”-style runtime errors.
  • Aim to enable strict to get the most thorough checking that TypeScript can offer.

Code Samples

function add(a, b) {
  return a + b;
}
add(10, null);

💻 playground


function add(a, b) {
  return a + b;
}

💻 playground


function add(a, b) {
  //         ~    Parameter 'a' implicitly has an 'any' type
  //            ~ Parameter 'b' implicitly has an 'any' type
  return a + b;
}

💻 playground


function add(a: number, b: number) {
  return a + b;
}

💻 playground


const x: number = null;  // OK, null is a valid number

💻 playground


const x: number = null;
//    ~ Type 'null' is not assignable to type 'number'

💻 playground


const x: number | null = null;

💻 playground


const statusEl = document.getElementById('status');
statusEl.textContent = 'Ready';
// ~~~~~ 'statusEl' is possibly 'null'.

if (statusEl) {
  statusEl.textContent = 'Ready';  // OK, null has been excluded
}
statusEl!.textContent = 'Ready';  // OK, we've asserted that el is non-null

💻 playground


const tenses = ['past', 'present', 'future'];
tenses[3].toUpperCase();

💻 playground


const tenses = ['past', 'present', 'future'];
tenses[3].toUpperCase();
// ~~~~~~ Object is possibly 'undefined'.

💻 playground


tenses[0].toUpperCase();
// ~~~~~~ Object is possibly 'undefined'.

💻 playground