What is TypeScript?
TypeScript is JavaScript with a type system that catches mistakes before your code runs.
Syntax
let message: string = "Hello";TypeScript is an open-source language built on top of JavaScript. It adds static types — a way to describe the shape of your data — so the compiler can catch bugs while you write code, not after it ships.
Why learn TypeScript?
- Catches typos and type mismatches before running.
- Gives you autocomplete and inline documentation in your editor.
- Every valid JavaScript program is also a valid TypeScript program.
TypeScript code is transpiled (compiled) down to plain JavaScript that runs anywhere JavaScript runs — browsers, Node.js, and beyond.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A large React codebase switches to TypeScript to catch prop-type mismatches at build time instead of in production.
- A Node.js API team adds TypeScript so IDE autocomplete works across dozens of service modules.
- A library author ships TypeScript declaration files so consumers get inline documentation and type checking.
More examples
Plain JS vs typed TS
Shows how TypeScript surfaces a type mismatch that plain JavaScript only catches at runtime.
// JavaScript: no error until runtime
function greet(name) {
return 'Hello, ' + name.toUpperCase();
}
greet(42); // TypeError at runtime
// TypeScript: caught at compile time
function greetTS(name: string): string {
return 'Hello, ' + name.toUpperCase();
}
greetTS(42); // Error: Argument of type 'number' is not assignableInstall and initialise TypeScript
Installs the TypeScript compiler locally and generates a tsconfig.json with sensible defaults.
npm install --save-dev typescript
npx tsc --initCompile a TypeScript file
Demonstrates the two most common ways to invoke the TypeScript compiler from the terminal.
# Compile once
npx tsc index.ts
# Watch mode: recompile on every save
npx tsc --watch
Discussion