Module 4

TypeScript

JavaScript with types. Catch bugs while you type, get better autocomplete, and refactor with confidence. This page goes from string and number to generics, mapped types and conditional types.

Types & interfaces Narrowing Generics Utility types TS + React
Level 1 β€” BasicsWhy TypeScript, setup, primitive types, arrays, objects, functions and unions

Why TypeScript? Basic

TypeScript is a superset of JavaScript: every JS file is already valid TS. It adds static types, which are checked before your code runs. Browsers can't run TS, so it is compiled to plain JavaScript first.

How TypeScript works
app.tsyour code + types
tsc / bundler
Type checkerrors shown in editor
types erased
app.jsplain JavaScript
runs in
Browser / Node

Types exist only at compile time. They are completely removed in the output.

JavaScript β€” bug found by users
TypeScript β€” bug found in editor
Think of it like thisTypes are like labelled containers: you can't pour juice into the box marked "only screws". A spell-checker for your logic.

Setup Basic

In Next.jscreate-next-app sets up TypeScript for you. Rename a file to .ts or .tsx and it just works. Recent Node.js versions can also run .ts files directly by stripping the types.

Basic types & inference Basic

TypeMeaningUse?
anyTurns type checking offAvoid. It hides bugs.
unknown"Could be anything, so check it before use"Use for untrusted data (JSON, catch errors)
voidThe function returns nothingReturn type of handlers
neverA value that can never existExhaustive checks, functions that always throw

Arrays, tuples & objects Basic

Type aliases & interfaces Basic

Give a shape a name so you can reuse it.

Featuretypeinterface
Object shapesβœ“βœ“
Unions / primitives / tuplesβœ“βœ—
Extend&extends
Declaration mergingβœ—βœ“
Mapped / conditional typesβœ“βœ—
Which one?Either is fine. Pick one and stay consistent. A common rule is interface for object/class shapes and type for everything else.

Functions Basic

Union & literal types Basic

A union (A | B) means "either A or B". A literal type allows only exact values.

type Status = "idle" | "loading" | "success" | "error"
"idle""loading""success""error" "done""pending"42

Only the highlighted values are allowed. Typos like "sucess" are caught right away.

Enums vs union of literals

Level 2 β€” IntermediateNarrowing, generics, utility types, keyof/typeof and classes

Narrowing & type guards Intermediate

Narrowing is how TS works out a more specific type inside an if block, based on the checks you write.

Narrowing string | number
value: string | number
typeof === "string"
string.toUpperCase() βœ“
else
number.toFixed() βœ“

Discriminated unions (very common!)

Generics Intermediate

Generics are type parameters. They let one function or type work with many types without losing type information.

Labelled boxBox<T> is a box whose label you fill in later. Box<Shoe> holds shoes and Box<Book> holds books. It's the same box design, and you always know what's inside.
T flows from input to output
first([1,2,3])T = number
function first<T>(arr: T[]): T
returns number

Utility types Intermediate

Built-in helpers that transform existing types, so you don't have to rewrite them.

Starting from User { id; name; email; password }
Partial<User>

all fields optional β†’ great for PATCH updates

Required<User>

all fields required

Pick<User, "id" | "name">

only id, name

Omit<User, "password">

everything except password β†’ safe public user

Readonly<User>

no field can be reassigned

Record<K, V>

object with keys K and values V

keyof, typeof & indexed access Intermediate

Classes Intermediate

ModifierAccessible from
public (default)Anywhere
protectedThe class and its subclasses
private / #fieldOnly the class (# is also enforced at runtime)
readonlySet once in the constructor
Level 3 β€” AdvancedMapped types, conditional types, infer, template literals, declaration files, tsconfig and TS with React

Mapped types Advanced

A mapped type loops over the keys of a type and builds a new one. This is how Partial and Readonly are built.

{ [K in keyof T]: … }
{ name: string; age: number }
for each key K
K β†’ () => T[K]
result
{ getName(): string; getAge(): number }

Conditional types & infer Advanced

The syntax is T extends U ? X : Y, which works like a ternary operator for types. With infer you can pull a type out of another type.

Template literal types Advanced

Modules & declaration files Advanced

@types packagesMany libraries ship with their own types. For those that don't, install community types: npm i -D @types/pg. They come from the DefinitelyTyped project.

tsconfig.json essentials Advanced

strict enables…Catches
strictNullChecksUsing a value that may be null/undefined
noImplicitAnyParameters with no type
strictFunctionTypesUnsafe function assignments
strictPropertyInitializationClass fields never set

TypeScript with React & Next.js Advanced

Share types end-to-endDefine a Zod schema once and use z.infer. The same type then covers the form (frontend), the validation (backend) and the DB insert. One source of truth.
Practice & ReviewQuiz, interview questions and a cheat sheet

Interview questions

Which type should you give to JSON.parse() results from an API?

You want a User type without the password field. Use…

Both describe object shapes. type can also express unions, tuples, primitives, mapped types and conditional types. interface supports declaration merging and extends. Choose one and be consistent.

Generics are type parameters. You write one function or type that works with many types and keeps the relationship between input and output types, for example first<T>(arr: T[]): T.

It checks that a value matches a type without changing the value's inferred type. You get validation and still keep the precise literal types.

No. Types are erased at compile time. Data from outside your program (API responses, form input) needs runtime validation with something like Zod.

Cheat sheet

Basics
  • x: stringannotate
  • a?: Toptional
  • A | Bunion
  • A & Bintersection
  • T[] / [A, B]array / tuple
Utilities
  • Partial / Requiredoptional-ness
  • Pick / Omitselect keys
  • Record<K,V>map
  • ReturnType / Awaitedextract
Operators
  • keyof Tkeys union
  • typeof xtype of value
  • T[K]indexed
  • as constliteral
  • satisfiescheck only
Advanced
  • <T extends X>constraint
  • [K in keyof T]mapped
  • T extends U ? X : Yconditional
  • infer Rextract
  • x is Ttype guard
TypeScript notes