TypeScript Basics
Adding static types to JavaScript — type annotations and inference, interfaces vs type aliases, unions and narrowing, functions, generics, classes, enums vs union literals, tsconfig, and how types are erased at runtime.
TypeScript is JavaScript with a static type system. You write .ts files; the TypeScript compiler (tsc) checks the types and emits plain JavaScript with the types erased. Every JavaScript program is (almost) valid TypeScript, so you can adopt it gradually. It catches typos, null mistakes and wrong arguments before code runs, and powers editor autocomplete and safe refactoring.
Annotations and inference
let count: number = 0;
const name = "Ada"; // inferred as the literal type "Ada" (const)
let title = "Engineer"; // inferred as string
const scores = [90, 85]; // number[]
let id: string | number; // union
function add(a: number, b: number): number { // parameters need annotations; return is inferable
return a + b;
}
add(1, "2"); // ✗ Argument of type 'string' is not assignable to 'number'Annotate function boundaries (parameters, exported APIs); let inference handle the rest.
The basic types
| Type | Example |
|---|---|
string, number, boolean, bigint, symbol | primitives |
null, undefined | with strictNullChecks, only assignable where allowed |
string[] / Array<string> | arrays |
[string, number] | tuple |
"GET" | "POST" | literal union |
unknown | any value, but you must narrow before using it — safe |
any | opts out of checking — avoid |
never | no value possible (exhaustive checks, functions that always throw) |
void | function returns nothing useful |
object, Record<string, number> | non-primitive / dictionary |
Object types: interface vs type
interface User {
id: string;
name: string;
email?: string; // optional
readonly createdAt: Date; // can't be reassigned
}
type Point = { x: number; y: number };
type ID = string | number; // type aliases can name ANY type
type Handler = (event: MouseEvent) => void; // function type
interface Admin extends User { permissions: string[] } // extension
type AdminT = User & { permissions: string[] }; // intersectioninterface | type | |
|---|---|---|
| Object shapes | ✓ | ✓ |
| Unions, primitives, tuples, mapped types | ✗ | ✓ |
extends / implements | ✓ | via & |
| Declaration merging (re-open to add fields) | ✓ | ✗ |
Either is fine for objects; many teams use interface for object shapes and type for everything else. Be consistent.
Structural typing
TypeScript checks shapes, not names. Any object with the right properties fits:
function greet(u: { name: string }) { return `Hi ${u.name}`; }
const dog = { name: "Rex", breed: "lab" };
greet(dog); // ✓ dog has a name: string
greet({ name: "Rex", breed: "lab" }); // ✗ excess property check on fresh object literalsUnions and narrowing
A union value could be any member; TypeScript narrows it as you check:
function format(value: string | number | Date): string {
if (typeof value === "string") return value.trim(); // value: string
if (typeof value === "number") return value.toFixed(2); // value: number
return value.toISOString(); // value: Date
}
function len(x: string[] | null) {
if (!x) return 0; // truthiness narrowing removes null
return x.length;
}Narrowing works with typeof, instanceof, in, equality checks, truthiness, Array.isArray, and discriminated unions — the most useful pattern in TypeScript:
type Result =
| { status: "success"; data: User[] }
| { status: "error"; error: string }
| { status: "loading" };
function render(r: Result) {
switch (r.status) {
case "success": return r.data.map((u) => u.name); // r.data available here
case "error": return `Failed: ${r.error}`;
case "loading": return "Loading…";
default: {
const exhaustive: never = r; // compile error if a new status is added and not handled
return exhaustive;
}
}
}Custom type guards
function isUser(x: unknown): x is User {
return typeof x === "object" && x !== null && "id" in x && "name" in x;
}
const data: unknown = await res.json();
if (isUser(data)) console.log(data.name);Functions
function greet(name: string, greeting = "Hello", punctuation?: string): string {
return `${greeting}, ${name}${punctuation ?? "!"}`;
}
const sum = (...nums: number[]): number => nums.reduce((a, b) => a + b, 0);
// Overloads: several call signatures, one implementation
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]) {
return Array.isArray(input) ? input.map(Number) : Number(input);
}Generics
Types that take type parameters, keeping the relationship between inputs and outputs:
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([1, 2, 3]); // number | undefined
const s = first(["a"]); // string | undefined
// Constraints
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
// Generic types
interface ApiResponse<T> { data: T; error?: string }
type UsersResponse = ApiResponse<User[]>;
async function getJson<T>(url: string): Promise<T> {
const res = await fetch(url);
return res.json() as Promise<T>; // a cast: TS can't verify the server — validate in real code
}Classes
class Account {
private balance = 0; // compile-time private (use #balance for runtime privacy)
constructor(public readonly owner: string) {} // parameter property: declares + assigns
deposit(amount: number): void { this.balance += amount; }
get current(): number { return this.balance; }
}
interface Shape { area(): number }
abstract class Base implements Shape {
abstract area(): number;
describe() { return `Area ${this.area()}`; }
}Enums vs literal unions
enum Direction { Up, Down } // generates a runtime object; numeric enums allow any number
type Dir = "up" | "down"; // no runtime cost, great inference — usually preferred
const Status = { Active: "active", Banned: "banned" } as const;
type Status = (typeof Status)[keyof typeof Status]; // "active" | "banned"Types are erased
TypeScript types don't exist at runtime. They can't validate data from APIs, forms or files — a User annotation on JSON.parse output is a promise you're making, not a check. Validate external data at the boundary with a schema library (zod, valibot, ArkType) that also gives you the static type:
import { z } from "zod";
const UserSchema = z.object({ id: z.string(), name: z.string(), email: z.string().email().optional() });
type User = z.infer<typeof UserSchema>;
const user = UserSchema.parse(await res.json()); // throws if the shape is wrongtsconfig essentials
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"skipLibCheck": true,
"outDir": "dist"
},
"include": ["src"]
}"strict": true enables strictNullChecks, noImplicitAny and more — always turn it on. Modern runtimes (Node 23+, Deno, Bun) can run .ts directly by stripping types; tsc --noEmit is then used purely for type checking.
- TypeScript adds static types to JavaScript; types are checked at compile time and erased.
- Annotate function boundaries; let inference do the rest.
- Typing is structural; interfaces and type aliases both describe shapes.
- Unions + narrowing, especially discriminated unions with exhaustive never checks, model states safely.
- Generics preserve type relationships; prefer unknown over any.
- Validate external data at runtime (zod); enable strict mode.