Course outline · 0% complete

0/26 lessons0%

Course overview →

What TypeScript Is

lesson 1-1 · ~9 min · 1/26

JavaScript with a safety net

You already write JavaScript, so you already know its biggest weakness: it happily runs broken code. This JS function looks fine and crashes at runtime:

function greet(user) {
  return "Hello, " + user.name.toUpperCase();
}

greet("Alice"); // crash: user.name is undefined

JavaScript only discovers the problem while the program is running, maybe in front of a user.

TypeScript is JavaScript plus a type system: a way to declare what kind of value each variable and parameter holds. A type is a category of values, like string or number. Before your code runs, the TypeScript compiler (a program called tsc) reads your annotations and checks every line. If you pass a string where an object is required, it refuses to compile and points at the exact line.

Types disappear at runtime

TypeScript is a compile-time layer. The compiler checks your code, then strips out every annotation and emits plain JavaScript. The browser or Node never sees a type. That means:

  • Valid TypeScript behaves exactly like the JavaScript you know
  • Types cost nothing at runtime, they are checks and documentation
  • Any JavaScript file is already almost valid TypeScript

The workflow is: write .ts files, the compiler checks them, and out comes .js that runs anywhere JavaScript runs. In this course the Run button does that whole pipeline for you in an isolated sandbox.

app.tsyour code + typestscchecks every lineapp.jsplain JS, runserrors are reported here, before anything runs
The TypeScript pipeline: your .ts file passes through the compiler, which checks types and emits plain JavaScript.

Code exercise · typescript

Your first TypeScript program. Each variable declares its type after a colon. Run it, then try changing firstRelease to the string "2012" and run again to watch the compiler complain.

Quiz

When does TypeScript report a type error, such as passing a string to a function that expects a number?