Why TypeScript?
It catches errors before they hit production.
// JavaScript - fails at runtime
function greet(name) {
return name.toUpperCase();
}
greet(123); // Runtime error
// TypeScript - fails at compile time
function greet(name: string): string {
return name.toUpperCase();
}
greet(123); // Compile error
Basic Types
let name: string = "Matt";
let age: number = 30;
let active: boolean = true;
let items: string[] = ["a", "b"];
let tuple: [string, number] = ["hello", 10];
Interfaces
interface User {
id: number;
name: string;
email: string;
role?: string; // Optional
}
function getUser(id: number): User {
// ...
}
Type Inference
TypeScript is smart. Let it work:
// Explicit (unnecessary)
const name: string = "Matt";
// Inferred (preferred)
const name = "Matt"; // TypeScript knows it's a string
Union Types
function formatId(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase();
}
return id.toString();
}
Generics
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
first([1, 2, 3]); // number
first(["a", "b"]); // string
Getting Started
npm install typescript --save-dev
npx tsc --init
Start with relaxed settings, tighten as you go:
{
"compilerOptions": {
"strict": false,
"noImplicitAny": false
}
}
