From JavaScript to TypeScript

JavaScript is flexible and forgiving, and it runs everywhere. That flexibility has a cost. In a large codebase there is no type information to check against, so bugs are harder to catch, and when you refactor you have no way to be confident that a change is safe. TypeScript was created to solve that problem.

// This JavaScript can silently produce bugs
function calculateTotal(price, quantity) {
  return price * quantity;
}

calculateTotal("19.99", 3);  // 59.97 (string is silently coerced)
calculateTotal("19.99 USD", 3);  // NaN — bad input slips through

TypeScript is a statically typed superset of JavaScript, developed by Microsoft and first released in 2012. “Superset” means that every valid JavaScript program is also a valid TypeScript program. TypeScript adds optional type annotations and a compiler that catches mistakes before your code runs.

function calculateTotal(price: number, quantity: number): number {
  return price * quantity;
}

calculateTotal("19.99", 3);
// Error: Argument of type 'string' is not assignable
//        to parameter of type 'number'

The TypeScript compiler (tsc) checks your code for type errors and then erases all the type information, producing plain JavaScript that runs anywhere JavaScript runs. So the checking happens while you develop, and the code that ships has no runtime overhead from it.

TypeScript is widely used. Angular adopted it as its primary language, React and Vue support TypeScript, and most major libraries ship with type definitions.

In this chapter, we will cover the essentials of TypeScript for JavaScript developers — how to set it up, the type system basics, advanced types, and best practices.

Learning Outcomes

  • Explain why TypeScript exists and set up a TypeScript project with the compiler
  • Annotate variables, functions, and classes with TypeScript’s basic and composed types
  • Use advanced type features, including generics, tuples, enums, and type narrowing, to write flexible and type-safe code
  • Apply TypeScript best practices to write idiomatic, safe code

Sections

  1. Getting Started with TypeScript
  2. Type Annotations and Basic Types
  3. Functions and Interfaces
  4. Composing Types
  5. Generics, Tuples, and Enums
  6. Type Narrowing and Runtime Behavior
  7. Best Practices
  8. Practice Questions