TypeScript Complete Guide with Examples and Output
A practical, example-driven guide from first steps to advanced types. Every example shows the expected output as a comment.
1. Introduction and Setup
TypeScript is a superset of JavaScript that adds a static type system. Code is type-checked at compile time, then compiled to plain JavaScript.
npm install -g typescript
tsc --version # Version 5.x
mkdir ts-demo && cd ts-demo
npm init -y
tsc --init # creates tsconfig.json
Create hello.ts:
const message: string = "Hello, TypeScript!";
console.log(message);
Compile and run:
tsc hello.ts
node hello.js
# Output: Hello, TypeScript!
You can also run directly with npx tsx hello.ts or ts-node hello.ts.
A type error is caught before the code runs:
let age: number = 25;
age = "twenty five";
// Error: Type 'string' is not assignable to type 'number'.
2. Basic Types
const username: string = "Alice";
const age: number = 30;
const price: number = 19.99;
const isActive: boolean = true;
const big: bigint = 9007199254740993n;
const id: symbol = Symbol("id");
const nothing: null = null;
let notSet: undefined = undefined;
console.log(typeof username, typeof age, typeof isActive, typeof big);
// Output: string number boolean bigint
any, unknown, never, void
// any: turns off type checking (avoid)
let anything: any = 5;
anything = "now a string";
anything.foo.bar; // no compile error, crashes at runtime
// unknown: safe alternative to any, must narrow before use
let value: unknown = "hello";
if (typeof value === "string") {
console.log(value.toUpperCase());
}
// Output: HELLO
// void: function returns nothing
function logMsg(msg: string): void {
console.log(msg);
}
logMsg("Done"); // Output: Done
// never: function never returns
function fail(msg: string): never {
throw new Error(msg);
}
3. Type Inference and Annotations
TypeScript infers types when it can, so you do not need to annotate everything.
let city = "Paris"; // inferred: string
let count = 10; // inferred: number
const PI = 3.14; // inferred: literal type 3.14
city = 42; // Error: Type 'number' is not assignable to type 'string'.
const nums = [1, 2, 3]; // number[]
const result = nums.map(n => n * 2);
console.log(result);
// Output: [ 2, 4, 6 ]
Annotate function parameters, public APIs, and variables declared without a value.
4. Arrays, Tuples, Enums
Arrays
const fruits: string[] = ["apple", "banana"];
const scores: Array<number> = [90, 85];
fruits.push("cherry");
console.log(fruits, scores.length);
// Output: [ 'apple', 'banana', 'cherry' ] 2
fruits.push(5); // Error: Argument of type 'number' is not assignable to 'string'.
const readonlyList: readonly number[] = [1, 2, 3];
readonlyList.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.
Tuples
const person: [string, number] = ["Alice", 30];
console.log(person[0], person[1]);
// Output: Alice 30
const point: [x: number, y: number, z?: number] = [1, 2];
console.log(point);
// Output: [ 1, 2 ]
const [name, personAge] = person;
console.log(name, personAge);
// Output: Alice 30
Enums
enum Direction {
Up,
Down,
Left,
Right,
}
console.log(Direction.Up, Direction.Right, Direction[1]);
// Output: 0 3 Down
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
}
console.log(Status.Active);
// Output: ACTIVE
const enum Color { Red = "RED", Blue = "BLUE" } // inlined at compile time
console.log(Color.Red);
// Output: RED
Modern alternative to enums: a union of string literals (see section 7).
5. Functions
function add(a: number, b: number): number {
return a + b;
}
console.log(add(2, 3));
// Output: 5
add(2, "3"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
const multiply = (a: number, b: number): number => a * b;
console.log(multiply(4, 5));
// Output: 20
Optional, default, and rest parameters
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
console.log(greet("Sam")); // Output: Hello, Sam!
console.log(greet("Sam", "Hi")); // Output: Hi, Sam!
function power(base: number, exp: number = 2): number {
return base ** exp;
}
console.log(power(5)); // Output: 25
console.log(power(2, 10)); // Output: 1024
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Function types and overloads
type MathFn = (a: number, b: number) => number;
const subtract: MathFn = (a, b) => a - b;
console.log(subtract(10, 4));
// Output: 6
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
return typeof value === "string" ? value.trim() : value.toFixed(2);
}
console.log(format(" hi ")); // Output: hi
console.log(format(3.14159)); // Output: 3.14
this parameter and callbacks
function runTwice(cb: (i: number) => void): void {
cb(1);
cb(2);
}
runTwice(i => console.log("call", i));
// Output:
// call 1
// call 2
6. Objects, Interfaces, and Type Aliases
const user: { name: string; age: number; email?: string } = {
name: "Alice",
age: 30,
};
console.log(user);
// Output: { name: 'Alice', age: 30 }
Interfaces
interface User {
readonly id: number;
name: string;
email?: string;
}
const u: User = { id: 1, name: "Bob" };
u.name = "Robert";
console.log(u);
// Output: { id: 1, name: 'Robert' }
u.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
Extending interfaces
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const dog: Dog = { name: "Rex", breed: "Labrador" };
console.log(dog);
// Output: { name: 'Rex', breed: 'Labrador' }
Type aliases
type Point = { x: number; y: number };
type ID = string | number;
const p: Point = { x: 10, y: 20 };
const userId: ID = "abc123";
console.log(p, userId);
// Output: { x: 10, y: 20 } abc123
interface vs type: interfaces can be merged (declaration merging) and are great for object shapes and classes. Type aliases can name unions, tuples, and primitives. Either works for plain objects; pick one and stay consistent.
Index signatures
interface Dictionary {
[key: string]: number;
}
const ages: Dictionary = { alice: 30, bob: 25 };
ages.carol = 22;
console.log(ages);
// Output: { alice: 30, bob: 25, carol: 22 }
7. Union, Intersection, and Literal Types
function printId(id: string | number): void {
console.log("ID:", id);
}
printId(101); // Output: ID: 101
printId("A-7"); // Output: ID: A-7
type Direction = "north" | "south" | "east" | "west";
let heading: Direction = "north";
heading = "up"; // Error: Type '"up"' is not assignable to type 'Direction'.
type HttpCode = 200 | 404 | 500;
Intersection
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
const p: Person = { name: "Zoe", age: 28 };
console.log(p);
// Output: { name: 'Zoe', age: 28 }
const assertions and satisfies
const config = { host: "localhost", port: 3000 } as const;
config.port = 4000; // Error: Cannot assign to 'port' because it is a read-only property.
type Colors = Record<string, [number, number, number] | string>;
const palette = {
red: [255, 0, 0],
green: "#00ff00",
} satisfies Colors;
console.log(palette.red.map(n => n / 255));
// Output: [ 1, 0, 0 ]
8. Type Narrowing and Guards
function describe(x: string | number | boolean): string {
if (typeof x === "string") return `string of length ${x.length}`;
if (typeof x === "number") return `number ${x.toFixed(1)}`;
return `boolean ${x}`;
}
console.log(describe("hello")); // Output: string of length 5
console.log(describe(42)); // Output: number 42.0
console.log(describe(true)); // Output: boolean true
instanceof and in
class Cat { meow() { return "meow"; } }
class Bird { chirp() { return "chirp"; } }
function sound(pet: Cat | Bird): string {
return pet instanceof Cat ? pet.meow() : pet.chirp();
}
console.log(sound(new Cat())); // Output: meow
console.log(sound(new Bird())); // Output: chirp
type Fish = { swim: () => string };
type Human = { walk: () => string };
function move(a: Fish | Human): string {
return "swim" in a ? a.swim() : a.walk();
}
console.log(move({ swim: () => "swimming" }));
// Output: swimming
Custom type guards
interface Car { drive(): string }
interface Boat { sail(): string }
function isCar(v: Car | Boat): v is Car {
return (v as Car).drive !== undefined;
}
const vehicle: Car | Boat = { drive: () => "vroom" };
if (isCar(vehicle)) {
console.log(vehicle.drive());
}
// Output: vroom
Discriminated unions
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rect"; w: number; h: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "square": return s.size ** 2;
case "rect": return s.w * s.h;
default: {
const _exhaustive: never = s; // compile error if a case is missing
return _exhaustive;
}
}
}
console.log(area({ kind: "circle", radius: 2 }).toFixed(2)); // Output: 12.57
console.log(area({ kind: "rect", w: 3, h: 4 })); // Output: 12
Optional chaining and nullish coalescing
interface Profile { address?: { city?: string } }
const profile: Profile = {};
console.log(profile.address?.city ?? "Unknown");
// Output: Unknown
9. Classes
class Person {
name: string;
private age: number;
protected nickname: string;
static count = 0;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
this.nickname = name.toLowerCase();
Person.count++;
}
greet(): string {
return `Hi, I'm ${this.name} and I'm ${this.age}`;
}
}
const p = new Person("Alice", 30);
console.log(p.greet()); // Output: Hi, I'm Alice and I'm 30
console.log(Person.count); // Output: 1
console.log(p.age); // Error: Property 'age' is private.
Parameter properties, getters, setters
class Account {
constructor(public owner: string, private _balance: number = 0) {}
get balance(): number {
return this._balance;
}
set balance(v: number) {
if (v < 0) throw new Error("Negative balance");
this._balance = v;
}
}
const acc = new Account("Sam", 100);
acc.balance = 250;
console.log(acc.owner, acc.balance);
// Output: Sam 250
Inheritance, abstract classes, interfaces
abstract class Shape {
abstract area(): number;
describe(): string {
return `Area: ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(private r: number) { super(); }
area(): number { return Math.PI * this.r ** 2; }
}
console.log(new Circle(3).describe());
// Output: Area: 28.27
new Shape(); // Error: Cannot create an instance of an abstract class.
interface Printable { print(): void }
class Doc implements Printable {
print() { console.log("Printing document..."); }
}
new Doc().print();
// Output: Printing document...
readonly and ECMAScript private fields
class Secret {
readonly id = 1;
#hidden = "shh";
reveal() { return this.#hidden; }
}
console.log(new Secret().reveal());
// Output: shh
10. Generics
Generics let you write reusable code that works with many types while staying type-safe.
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("hello")); // Output: hello
console.log(identity(42)); // Output: 42 (T inferred as number)
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
console.log(first([10, 20, 30])); // Output: 10
console.log(first(["a", "b"])); // Output: a
console.log(first([])); // Output: undefined
Generic constraints
interface HasLength { length: number }
function longest<T extends HasLength>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
console.log(longest("apple", "fig")); // Output: apple
console.log(longest([1, 2], [1, 2, 3])); // Output: [ 1, 2, 3 ]
longest(10, 20); // Error: Argument of type 'number' is not assignable to 'HasLength'.
keyof and indexed access
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const car = { brand: "Toyota", year: 2022 };
console.log(getProp(car, "brand")); // Output: Toyota
console.log(getProp(car, "year")); // Output: 2022
getProp(car, "color"); // Error: Argument of type '"color"' is not assignable to '"brand" | "year"'.
Generic interfaces and classes
interface ApiResponse<T> {
data: T;
status: number;
}
const res: ApiResponse<{ id: number; name: string }> = {
data: { id: 1, name: "Item" },
status: 200,
};
console.log(res);
// Output: { data: { id: 1, name: 'Item' }, status: 200 }
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
get size(): number { return this.items.length; }
}
const stack = new Stack<number>();
stack.push(1);
stack.push(2);
console.log(stack.pop(), stack.size);
// Output: 2 1
stack.push("x"); // Error: Argument of type 'string' is not assignable to 'number'.
Default type parameters
interface Box<T = string> { value: T }
const a: Box = { value: "text" };
const b: Box<number> = { value: 5 };
console.log(a, b);
// Output: { value: 'text' } { value: 5 }
11. Utility Types
interface Todo {
title: string;
description: string;
done: boolean;
}
// Partial: all properties optional
const update: Partial<Todo> = { done: true };
// Required: all properties required
type StrictTodo = Required<Partial<Todo>>;
// Readonly
const fixed: Readonly<Todo> = { title: "A", description: "B", done: false };
fixed.done = true; // Error: Cannot assign to 'done' because it is a read-only property.
// Pick and Omit
type TodoPreview = Pick<Todo, "title" | "done">;
type TodoNoDesc = Omit<Todo, "description">;
const preview: TodoPreview = { title: "Learn TS", done: false };
console.log(preview);
// Output: { title: 'Learn TS', done: false }
// Record
const roles: Record<"admin" | "user", number> = { admin: 1, user: 2 };
console.log(roles);
// Output: { admin: 1, user: 2 }
// Exclude, Extract, NonNullable
type T1 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
type T2 = Extract<string | number, number>; // number
type T3 = NonNullable<string | null | undefined>; // string
// ReturnType, Parameters, Awaited
function makeUser() { return { id: 1, name: "A" }; }
type U = ReturnType<typeof makeUser>; // { id: number; name: string }
type P = Parameters<(a: string, b: number) => void>; // [a: string, b: number]
type R = Awaited<Promise<string>>; // string
12. Mapped, Conditional, and Template Literal Types
Mapped types
type Flags<T> = { [K in keyof T]: boolean };
interface Features { darkMode: string; beta: number }
type FeatureFlags = Flags<Features>;
const f: FeatureFlags = { darkMode: true, beta: false };
console.log(f);
// Output: { darkMode: true, beta: false }
// Remove readonly with -readonly, make optional with ?
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
Conditional types
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>; // "yes"
type B = IsString<number>; // "no"
type ElementType<T> = T extends (infer U)[] ? U : T;
type E1 = ElementType<number[]>; // number
type E2 = ElementType<string>; // string
Template literal types
type Event = "click" | "hover";
type Handler = `on${Capitalize<Event>}`;
// "onClick" | "onHover"
const h: Handler = "onClick";
console.log(h);
// Output: onClick
typeof and keyof typeof
const settings = { theme: "dark", fontSize: 14 };
type Settings = typeof settings; // { theme: string; fontSize: number }
type SettingKey = keyof typeof settings; // "theme" | "fontSize"
13. Modules and Namespaces
math.ts:
export function square(n: number): number {
return n * n;
}
export const PI = 3.14159;
export default class Calculator {
add(a: number, b: number) { return a + b; }
}
export type Operation = "add" | "sub";
main.ts:
import Calculator, { square, PI, type Operation } from "./math";
console.log(square(4)); // Output: 16
console.log(PI); // Output: 3.14159
console.log(new Calculator().add(2, 3)); // Output: 5
const op: Operation = "add";
Use import type { Foo } from "./foo" for type-only imports. Prefer ES modules over namespace in new code.
14. Asynchronous TypeScript
function delay(ms: number): Promise<string> {
return new Promise(resolve => setTimeout(() => resolve(`Waited ${ms}ms`), ms));
}
async function main(): Promise<void> {
console.log("Start");
const result = await delay(500);
console.log(result);
console.log("End");
}
main();
// Output:
// Start
// Waited 500ms (after about 0.5 seconds)
// End
Typed fetch and Promise.all
interface Post { id: number; title: string }
async function getPost(id: number): Promise<Post> {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Post;
}
async function run() {
const [a, b] = await Promise.all([getPost(1), getPost(2)]);
console.log(a.id, b.id);
}
run();
// Output: 1 2
15. Error Handling
class ValidationError extends Error {
constructor(message: string, public field: string) {
super(message);
this.name = "ValidationError";
}
}
function validateAge(age: number): void {
if (age < 0) throw new ValidationError("Age cannot be negative", "age");
}
try {
validateAge(-5);
} catch (err) { // err is 'unknown' under strict mode
if (err instanceof ValidationError) {
console.log(`${err.name}: ${err.message} (field: ${err.field})`);
} else {
throw err;
}
}
// Output: ValidationError: Age cannot be negative (field: age)
Result pattern (errors as values)
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function parseJson(text: string): Result<unknown> {
try {
return { ok: true, value: JSON.parse(text) };
} catch (e) {
return { ok: false, error: e as Error };
}
}
const r1 = parseJson('{"a":1}');
const r2 = parseJson("not json");
console.log(r1.ok, r2.ok);
// Output: true false
16. Decorators (TypeScript 5+)
Standard decorators are supported in TS 5.0 without the old experimental flag.
function logged<This, Args extends any[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext
) {
return function (this: This, ...args: Args): Return {
console.log(`Calling ${String(context.name)} with`, args);
return target.call(this, ...args);
};
}
class Calc {
@logged
add(a: number, b: number) { return a + b; }
}
console.log(new Calc().add(2, 3));
// Output:
// Calling add with [ 2, 3 ]
// 5
17. Declaration Files and Third-Party Types
npm install lodash
npm install --save-dev @types/lodash
For a JS library without types, declare it yourself in globals.d.ts:
declare module "untyped-lib" {
export function doThing(x: string): number;
}
declare global {
interface Window { appVersion: string }
}
export {};
Set "declaration": true in tsconfig to generate .d.ts files for your own library.
18. tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"esModuleInterop": true,
"skipLibCheck": true,
"sourceMap": true,
"declaration": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Key flags:
| Flag | Purpose |
|---|---|
strict | Enables all strict checks (always turn on) |
noImplicitAny | Errors when a type would be implicitly any |
strictNullChecks | null and undefined are not assignable to other types |
noUncheckedIndexedAccess | arr[i] is T | undefined |
target | JavaScript version to emit |
module | Module system to emit |
Useful commands:
tsc # compile the project
tsc --watch # recompile on change
tsc --noEmit # type-check only
19. Mini Project: Typed Todo Manager
interface Todo {
id: number;
title: string;
done: boolean;
}
class TodoList {
private todos: Todo[] = [];
private nextId = 1;
add(title: string): Todo {
const todo: Todo = { id: this.nextId++, title, done: false };
this.todos.push(todo);
return todo;
}
complete(id: number): boolean {
const todo = this.todos.find(t => t.id === id);
if (!todo) return false;
todo.done = true;
return true;
}
filter(predicate: (t: Todo) => boolean): Todo[] {
return this.todos.filter(predicate);
}
}
const list = new TodoList();
list.add("Learn TypeScript");
list.add("Build a project");
list.complete(1);
console.log(list.filter(t => t.done));
console.log(list.filter(t => !t.done));
// Output:
// [ { id: 1, title: 'Learn TypeScript', done: true } ]
// [ { id: 2, title: 'Build a project', done: false } ]
20. Best Practices
- Enable
strictmode in every project. - Prefer
unknownoverany, and narrow before use. - Let inference work; annotate function signatures and exported APIs.
- Model state with discriminated unions instead of optional flags.
- Use
readonlyandas constto prevent accidental mutation. - Prefer string literal unions over enums for simple cases.
- Avoid type assertions (
as) unless you truly know more than the compiler. - Use utility types (
Pick,Omit,Partial,Record) rather than duplicating types. - Validate external data at runtime (for example with Zod), since types vanish after compilation.
- Run
tsc --noEmitand a linter such as ESLint withtypescript-eslintin CI.
Quick Reference
| Concept | Syntax |
|---|---|
| Annotation | let x: number |
| Union | string | number |
| Intersection | A & B |
| Optional | prop?: string |
| Generic | function f<T>(x: T) |
| Type guard | x is Foo |
| keyof | keyof T |
| Mapped | { [K in keyof T]: ... } |
| Conditional | T extends U ? X : Y |
| Non-null assertion | value! |
| Satisfies | expr satisfies Type |
Next steps: build a small project with Node or React, read the official handbook at typescriptlang.org/docs, and practice at typescriptlang.org/play where you can see compiled output live.

No comments:
Post a Comment