The Complete TypeScript Guide
By Flavio
Published · Updated
Tagged: TypeScript
Learn TypeScript from scratch: setup, inference, primitives, objects, unions, functions, generics, type narrowing, tsconfig.json, and runtime validation.
If you already know some JavaScript and you want to learn TypeScript from scratch, this guide is for you.
TypeScript can look intimidating when you open a big codebase full of angle brackets and cryptic error messages. It does not have to be that way.
In this guide we start from zero. We learn what TypeScript actually is, install it, run our first file, and then add one concept at a time: basic types, functions, objects, unions, narrowing, generics, tsconfig.json, and runtime validation with Zod.
Every example, compiler error, and command in this guide was tested live on my Mac against these versions:
| Software | Version |
|---|---|
TypeScript (tsc) | 7.0.2 |
| Node.js | 22.23.5 |
| Zod | 4.6.7 |
JSON to TypeScript
Paste JSON and generate TypeScript interfaces with nested types and optional keys right in your browser.
What is TypeScript?
TypeScript is JavaScript with a type checker on top.
You write code that looks almost identical to JavaScript, plus optional labels (called types) that describe the shape of your data. Before your program ever runs, the TypeScript compiler reads those types and warns you about typos, missing properties, and mismatched function arguments.
Here is the single most important thing to understand on day one: browsers and Node.js do not run TypeScript types.
When your code runs, all the TypeScript syntax is stripped away and only plain JavaScript executes. That means TypeScript adds zero runtime overhead to your app.
Let’s see why this helps with a tiny JavaScript bug we have all written at least once.
Imagine a function that adds shipping to a price:
function addShipping(price, shipping) {
return price + shipping
}
const total = addShipping('100', 10)
console.log(total) // '10010'
JavaScript happily runs that code and prints '10010' instead of 110, because '100' was a string from a form input or URL parameter. Nothing crashes, and your checkout silently charges the wrong amount.
Now let’s write the same function in TypeScript:
function addShipping(price: number, shipping: number): number {
return price + shipping
}
const total = addShipping('100', 10)
Before you even run the file, your editor puts a red squiggle under '100', and the TypeScript compiler refuses to pass it:
src/pricing.ts:5:27 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
That is the whole promise of TypeScript. Instead of discovering bugs when a user clicks a button in production, you catch them the moment you write the line.
You also get a huge side benefit right inside your editor. Because TypeScript knows the exact properties on every object and the exact parameters of every function, autocomplete and safe renaming across dozens of files start working reliably.
Keep one limitation in mind right from the start: because types are erased before your code runs, TypeScript cannot inspect data coming from outside your program (like JSON from an API or text typed into a form). We will come back to that in Chapter 13 and solve it cleanly with Zod.
Installing TypeScript and running your first file
Let’s set up a small folder and run our first TypeScript file right away.
I always install TypeScript as a local dev dependency inside each project rather than globally. That way everyone working on the project uses the same compiler version.
Create a new folder, initialize package.json, and install TypeScript:
mkdir ts-demo
cd ts-demo
npm init -y
npm pkg set type=module
npm install -D typescript
Now ask TypeScript to generate a starter tsconfig.json file:
npx tsc --init
We will go deep into tsconfig.json in Chapter 12. For now, replace the generated file with this short, clean config so you know what every single line does:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["src"]
}
Create a src folder and add src/hello.ts:
const name: string = 'Flavio'
console.log(`Hello, ${name}!`)
Let’s run it. On Node.js 22 (and Bun), you can execute .ts files directly without any build step:
node src/hello.ts
It prints:
Hello, Flavio!
Now here is a trap that catches almost every beginner who runs TypeScript directly with Node.js or Bun: Node.js strips your types without checking them.
Let’s prove it. Create src/pricing.ts with our buggy shipping example:
function addShipping(price: number, shipping: number): number {
return price + shipping
}
const total = addShipping('100', 10)
console.log(total)
If you run node src/pricing.ts, Node ignores : number, runs the JavaScript, and prints 10010 with zero warnings.
To check your types, run the TypeScript compiler with --noEmit:
npx tsc --noEmit
Now TypeScript catches the bug immediately:
src/pricing.ts:5:27 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
5 const total = addShipping("100", 10)
~~~~~
I run npx tsc --noEmit constantly in my terminal and in CI. The --noEmit flag tells tsc to check every file in your project without writing .js files to disk, which is what you want whenever Node, Bun, Vite, Astro, or Next.js runs your code.
When you want compiled .js files
Sometimes you do want TypeScript to output plain JavaScript files into a dist/ folder (for example, to run on an older Node version that does not strip types).
In that case, remove "noEmit": true from tsconfig.json, add "outDir": "dist" and "rootDir": "src", and run:
npx tsc
TypeScript compiles src/hello.ts into dist/hello.js, and you run it with node dist/hello.js.
Basic types and type inference
Now that you can run and check TypeScript files, let’s learn how types work on everyday variables.
Primitive types
JavaScript has three primitive types you will annotate all the time: string, number, and boolean.
const city: string = 'Milan'
const population: number = 1370000
const isCapital: boolean = false
Always use the lowercase names (string, number, boolean). Uppercase String, Number, and Boolean refer to JavaScript’s wrapper objects, which you almost never want.
JavaScript also has bigint for very large integers and symbol for unique keys:
const bigNumber: bigint = 9007199254740993n
const tokenKey: symbol = Symbol('token')
Let TypeScript infer obvious types
Wait a second. Look back at those lines we just wrote:
const city: string = 'Milan'
const population: number = 1370000
const isCapital: boolean = false
You do not actually need to write : string, : number, or : boolean there.
TypeScript looks at 'Milan' and immediately knows city is a string. That feature is called type inference, and letting it do the boring work keeps your code clean and readable:
const city = 'Milan' // inferred as 'Milan' (a string)
let count = 0 // inferred as number
let isReady = false // inferred as boolean
If you try count = 'five' on the next line, TypeScript still catches the error even though you never wrote : number.
So when should you write explicit type annotations?
- Function parameters. TypeScript cannot guess what callers will pass into a function.
- Variables declared without an initial value. For example,
let score: numberbefore assigningscore = 42later. - Empty arrays.
const names = []gives TypeScript no clues about what will go inside, so writeconst names: string[] = []. - Public API boundaries. Explicit return types on exported functions protect callers from accidental changes.
const vs let inference
Notice something subtle in the example above.
When you use let, TypeScript infers a broad type like string, because you might reassign it later:
let role = 'member' // inferred type: string
role = 'admin' // allowed
When you use const, the variable can never be reassigned, so TypeScript infers the exact literal type 'member':
const role = 'member' // inferred type: 'member'
That small detail will matter a lot when we get to union types in Chapter 6.
Arrays and tuples
To type an array, write the element type followed by []:
const fruits: string[] = ['apple', 'pear', 'banana']
const scores: number[] = [10, 20, 30]
You can also write Array<string> instead of string[]. Both mean the same thing, and I prefer string[] because it is shorter to read.
A tuple is a fixed-length array where each position has its own type. Tuples are handy for coordinates, RGB colors, or [key, value] pairs:
const point: [number, number] = [45.4642, 9.19]
const entry: [string, number] = ['TypeScript Handbook', 16]
If you try to assign ['Milan'] or [45.4642, 9.19, 100] to point, TypeScript flags an error right away.
You can even name tuple positions to make autocomplete clearer for your future self:
type Coordinates = [latitude: number, longitude: number]
const milan: Coordinates = [45.4642, 9.19]
Handling null and undefined
One of the most famous bugs in JavaScript is TypeError: Cannot read properties of undefined.
When "strict": true is turned on in tsconfig.json, TypeScript enables strictNullChecks. That means string cannot hold null or undefined unless you explicitly allow it with |:
let nickname: string | undefined
nickname = 'Flavio'
nickname = undefined
Before calling a string method on nickname, TypeScript forces you to check whether it exists:
function formatNickname(nickname: string | undefined) {
if (nickname === undefined) {
return 'Anonymous'
}
return nickname.toUpperCase()
}
Once you check nickname === undefined and return early, TypeScript knows nickname must be a string on the next line.
Optional chaining (?.) and nullish coalescing (??) pair nicely with strict null checks:
const length = nickname?.length ?? 0
Here nickname?.length produces number | undefined, and ?? 0 turns undefined into 0, so length is cleanly inferred as number.
Functions
Functions are where TypeScript pays off the fastest. Once you annotate a function’s parameters, TypeScript checks every single place in your codebase that calls it.
Parameters and return types
Put the type after each parameter name, and put the return type after the closing parenthesis:
function greet(name: string, times: number): string {
return `${name}! `.repeat(times).trim()
}
greet('Ada', 2) // 'Ada! Ada!'
Arrow functions use the same syntax:
const double = (value: number): number => value * 2
For short internal functions, you can omit the return type and let TypeScript infer it from your return statements. For exported functions or longer functions with multiple return branches, writing the return type explicitly catches mistakes where one branch accidentally returns the wrong shape.
Optional and default parameters
Add ? after a parameter name to make it optional:
function logMessage(message: string, prefix?: string) {
if (prefix) {
console.log(`[${prefix}] ${message}`)
return
}
console.log(message)
}
logMessage('Server started')
logMessage('Server started', 'BOOT')
Inside logMessage, prefix has the type string | undefined, so TypeScript makes sure you handle the missing case.
When a parameter has a default value, you do not need ?, and TypeScript can usually infer the type from the default value itself:
function paginate(page = 1, pageSize = 20) {
return { offset: (page - 1) * pageSize, limit: pageSize }
}
paginate() // page is 1, pageSize is 20
paginate(2) // page is 2, pageSize is 20
paginate(2, 50) // page is 2, pageSize is 50
Rest parameters
When a function accepts any number of arguments with ..., annotate the rest parameter as an array:
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0)
}
sum(1, 2, 3, 4) // 10
Typing callbacks and function types
When a function accepts another function as an argument, describe the callback with arrow syntax (param: Type) => ReturnType:
function transformText(value: string, formatter: (input: string) => string): string {
return formatter(value)
}
transformText('typescript', (text) => text.toUpperCase())
Notice you did not need to annotate (text) inside the callback. Because transformText declared formatter: (input: string) => string, TypeScript already knows text is a string.
The void return type
Use void when a function performs an action (like logging or saving to disk) and does not return a useful value:
function printDivider(label: string): void {
console.log(`--- ${label} ---`)
}
Typing destructured object parameters
This syntax trips up almost every developer moving from JavaScript to TypeScript.
In JavaScript, you write:
function sendEmail({ to, subject }) {
console.log(`Sending "${subject}" to ${to}`)
}
In TypeScript, { to: string } inside a destructuring pattern does not mean “type to as string” (in JavaScript destructuring, { to: recipient } renames the variable to to recipient).
Instead, put the object type after the entire destructuring pattern:
function sendEmail({ to, subject }: { to: string; subject: string }) {
console.log(`Sending "${subject}" to ${to}`)
}
Or even cleaner, extract a named type so the function signature stays easy to read:
type EmailOptions = {
to: string
subject: string
replyTo?: string
}
function sendEmail({ to, subject, replyTo }: EmailOptions) {
console.log(`Sending "${subject}" to ${to}`)
if (replyTo) console.log(`Reply-To: ${replyTo}`)
}
Objects, type aliases, and interfaces
Real apps pass objects around everywhere: users, orders, settings, API responses. Let’s see how to describe object shapes cleanly.
Describing object shapes
You can write an object type inline, with ? for optional fields and readonly for fields that should not be reassigned:
const book: {
readonly id: number
title: string
subtitle?: string
} = {
id: 1,
title: 'TypeScript Handbook',
}
Trying to run book.id = 2 produces a compile error because id is readonly.
Named shapes with type aliases
Inline object types get messy fast when you reuse the same shape in three functions. Give the shape a name with type:
type User = {
readonly id: number
name: string
email: string
bio?: string
}
function formatUser(user: User): string {
return `${user.name} <${user.email}>`
}
You can also combine two object types with an intersection (&), which produces a new type containing all properties from both:
type Timestamped = {
createdAt: Date
updatedAt: Date
}
type SavedUser = User & Timestamped
A SavedUser must have id, name, email, createdAt, and updatedAt.
Named shapes with interface
TypeScript also has the interface keyword for describing object shapes:
interface Article {
readonly slug: string
title: string
published: boolean
}
Interfaces extend other interfaces with the extends keyword:
interface FeaturedArticle extends Article {
featuredOrder: number
}
type vs interface: which one should you use?
Beginners spend way too much time worrying about this choice. For 95% of everyday object types, type and interface behave identically.
Here are the real differences:
| Feature | type | interface |
|---|---|---|
| Object shapes | Yes | Yes |
Optional (?) and readonly fields | Yes | Yes |
| Extending another shape | Intersection (&) | extends keyword |
Unions ('a' | 'b'), primitives, tuples | Yes | No |
| Declaration merging (same name declared twice) | Error | Merges automatically |
My advice is simple: use type by default for everything, because type handles objects, unions, tuples, and function signatures with one consistent syntax. Reach for interface if your team prefers it for object shapes, or if you are authoring a library that intentionally supports declaration merging.
Structural typing (shape matters, not the name)
TypeScript uses structural typing. That is a fancy way of saying TypeScript checks whether an object has the required properties, not whether it was created from a specific named type.
type Point = {
x: number
y: number
}
function distanceFromOrigin(point: Point): number {
return Math.hypot(point.x, point.y)
}
const cursor = { x: 3, y: 4, label: 'center' }
distanceFromOrigin(cursor) // 5 (works because cursor has x and y)
Notice cursor has an extra label property, and TypeScript still accepts it because it satisfies Point.
There is one helpful exception called excess property checking: if you pass an object literal directly into a typed variable or function call, TypeScript warns you about unknown properties because they are usually typos:
// Error: Object literal may only specify known properties, and 'z' does not exist in type 'Point'
distanceFromOrigin({ x: 3, y: 4, z: 5 })
Dynamic keys with index signatures and Record
Sometimes you do not know the exact property names ahead of time, like a dictionary mapping currency codes to exchange rates.
You can write an index signature:
type ExchangeRates = {
[currency: string]: number
}
const rates: ExchangeRates = {
EUR: 1,
USD: 1.08,
GBP: 0.85,
}
Or use the shorter built-in Record<Keys, Value> helper, which means the same thing:
const rates: Record<string, number> = {
EUR: 1,
USD: 1.08,
GBP: 0.85,
}
Union types, literal types, and narrowing
If there is one chapter that changes how you think about modeling data in JavaScript, it is this one.
Union types (|)
A union type says a value can be one of several types. Separate the options with |:
let userId: string | number
userId = 42
userId = 'usr_9f8a'
Unions are great for values that genuinely come in multiple shapes, like a function that accepts either a single tag or an array of tags:
function normalizeTags(input: string | string[]): string[] {
if (Array.isArray(input)) {
return input
}
return [input]
}
Literal types
Remember how const role = 'member' inferred the exact string 'member'? You can combine literal values into a union to lock down a small set of allowed options:
type OrderStatus = 'pending' | 'paid' | 'shipped' | 'cancelled'
let status: OrderStatus = 'pending'
status = 'paid'
// status = 'shiped' -> Compile error! Caught the typo.
You can do the same with numbers or booleans (type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6).
You may also see TypeScript’s enum keyword in older tutorials. I avoid enum in modern TypeScript because it emits extra JavaScript code at runtime and does not work with Node’s native type stripping. A literal union like 'pending' | 'paid' | 'shipped' gives you the same autocomplete and safety with zero runtime footprint.
Narrowing types safely
When a value has a union type like string | number, TypeScript only lets you call methods that exist on both string and number (like .toString()). Calling .toUpperCase() directly is an error because numbers do not have .toUpperCase().
Narrowing is how you prove to TypeScript which branch of the union you are currently inside, using normal JavaScript checks.
Let’s see that in code:
function formatValue(value: string | number | null): string {
if (value === null) {
return 'N/A'
}
if (typeof value === 'string') {
return value.toUpperCase()
}
return value.toFixed(2)
}
TypeScript follows your if and return statements automatically. By the last line, it has ruled out null and string, so it knows value must be a number.
Here are the narrowing checks you will use every day:
| Check | What it narrows | Example |
|---|---|---|
typeof x === 'string' | Primitives (string, number, boolean, bigint, symbol, undefined, function) | if (typeof id === 'number') |
x === null / x !== undefined | null and undefined | if (user === null) return |
Array.isArray(x) | Arrays vs non-arrays | if (Array.isArray(tags)) |
'prop' in x | Objects with a specific property | if ('error' in response) |
x instanceof Date | Class instances (Date, Error, Map) | if (err instanceof Error) |
x.status === 'ok' | Discriminated unions | if (result.status === 'success') |
Discriminated unions
This is my favorite pattern in all of TypeScript.
Imagine modeling the state of a network request. A messy way is one giant object with optional fields:
// Fragile: nothing stops loading: true AND error: 'Failed' at the same time
type MessyState = {
loading: boolean
data?: string[]
error?: string
}
A discriminated union models each possible state as its own clean object, sharing one common literal field (often called status, kind, or type):
type FetchState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; items: string[] }
| { status: 'error'; message: string }
Now invalid combinations are impossible to construct. And when you check state.status, TypeScript narrows the exact properties available in that state:
function renderStatus(state: FetchState): string {
switch (state.status) {
case 'idle':
return 'Ready'
case 'loading':
return 'Loading...'
case 'success':
return `Loaded ${state.items.length} items`
case 'error':
return `Something went wrong: ${state.message}`
}
}
Inside case 'success', TypeScript knows state.items exists. Inside case 'error', it knows state.message exists. No optional chaining, no guessing.
Special types: any, unknown, and never
Now that you know how types, unions, and narrowing work, we can look at three special types that confuse almost every newcomer when they see them without context.
any: turning the checker off
any tells TypeScript to stop checking a value completely.
let mystery: any = 'hello'
mystery = 42
mystery.nonExistentMethod() // No compile error, crashes at runtime!
The danger with any is that it spreads silently. If a function returns any, every variable that receives its output also loses type checking.
Avoid any in new code. The only time I reach for it is temporarily while migrating a messy JavaScript file to TypeScript, with a plan to replace it right after.
unknown: the safe way to handle mystery data
When you genuinely do not know a value’s type yet (like the output of JSON.parse() or an error caught in a catch block), use unknown.
unknown accepts any value, just like any, with one important difference: TypeScript will not let you use the value until you narrow it first.
function parseLength(input: unknown): number {
if (typeof input === 'string') {
return input.length
}
if (Array.isArray(input)) {
return input.length
}
return 0
}
Trying to write input.length before the if check gives a compile error. That forces you to handle the unknown value safely instead of hoping for the best.
never: values that cannot exist
never represents an impossible value. A function that always throws an error, or loops forever, has a return type of never because it never returns normally:
function fail(message: string): never {
throw new Error(message)
}
Where never becomes genuinely useful in daily code is exhaustive checking on discriminated unions.
Look back at our FetchState switch statement and add a default branch that assigns state to never:
function renderStatus(state: FetchState): string {
switch (state.status) {
case 'idle':
return 'Ready'
case 'loading':
return 'Loading...'
case 'success':
return `Loaded ${state.items.length} items`
case 'error':
return `Something went wrong: ${state.message}`
default: {
const unreachable: never = state
return unreachable
}
}
}
Right now every case is handled, so in default, state has been narrowed all the way down to never and the code compiles cleanly.
Six months later, when you add | { status: 'retrying'; attempt: number } to FetchState, TypeScript immediately flags const unreachable: never = state in every switch across your project until you handle the new 'retrying' state.
Comparing any, unknown, and never
| Type | What you can assign to it | What you can do with it directly | When to use it |
|---|---|---|---|
any | Anything | Anything (unsafe, turns off checks) | Almost never (temporary JS migrations only) |
unknown | Anything | Nothing until narrowed (typeof, instanceof, Zod) | Untrusted JSON, catch (err), generic inputs |
never | Nothing | Nothing (unreachable code) | Exhaustive switch checks, functions that always throw |
Type assertions (as), as const, and satisfies
Sometimes you know something about a value that TypeScript cannot see, like grabbing a specific HTML element from the DOM:
const input = document.querySelector('#email') as HTMLInputElement | null
Be careful with as. A type assertion does not convert or validate the value at runtime. It only tells the compiler to trust you. Writing (await res.json()) as User will still crash in production if the server sends back an error object instead of a User.
The same warning applies to the non-null assertion operator (!), as in user!.name. It tells TypeScript “I swear this is not null or undefined.” Prefer a real if check instead.
Two related operators are completely safe and super useful:
as constfreezes a value asreadonlyand keeps exact literal types instead of widening them tostringornumber:
const ROUTES = {
home: '/',
blog: '/blog',
ebooks: '/ebooks',
} as const
// ROUTES.home has type '/', not string
satisfieschecks that a value matches a type without throwing away its more specific inferred type:
type Palette = Record<string, string | [number, number, number]>
const theme = {
brand: '#2563eb',
accent: [16, 185, 129],
} satisfies Palette
// TypeScript still knows theme.brand is a string, so .toUpperCase() works!
theme.brand.toUpperCase()
If we had written const theme: Palette = ..., TypeScript would have forgotten whether theme.brand was a string or a tuple. satisfies gives you both validation and exact inference.
Generics without the headaches
Generics are the feature that scares beginners the most, mostly because people explain them with abstract letters before showing the problem they solve.
Let’s start with the problem.
Suppose you want a helper function that returns the first element of an array. If you write it for strings, it only works on strings:
function firstString(items: string[]): string | undefined {
return items[0]
}
If you rewrite it with any so it accepts numbers and objects too, you throw away all type safety:
function firstAny(items: any[]): any {
return items[0]
}
const lead = firstAny(['Ada', 'Grace']) // type is any (autocomplete is gone!)
A generic solves this by adding a type parameter (usually named T, for Type) in angle brackets <T>. Think of <T> just like a regular function parameter, except it holds a type instead of a value.
function first<T>(items: T[]): T | undefined {
return items[0]
}
const firstName = first(['Ada', 'Grace']) // inferred as string | undefined
const firstScore = first([10, 20, 30]) // inferred as number | undefined
You do not even need to write first<string>(['Ada', 'Grace']). TypeScript looks at the array you passed in, fills in T automatically, and preserves that exact type on the return value.
Generic types and interfaces
Generics are even more common on reusable wrapper types, like API responses or paginated lists:
type ApiResponse<T> = {
status: number
data: T
}
type Book = {
title: string
pages: number
}
const response: ApiResponse<Book> = {
status: 200,
data: { title: 'TypeScript Handbook', pages: 42 },
}
You can also give a generic parameter a default type with =:
type ApiResponse<T = unknown> = {
status: number
data: T
}
Constraining generics with extends
Inside a generic function, TypeScript assumes T could be anything, so you cannot access a.length unless you tell TypeScript that T must have a length property.
Use extends to set that minimum requirement:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b
}
longest('Milan', 'Turin') // 'Milan' (type: string)
longest([1, 2], [1, 2, 3]) // [1, 2, 3] (type: number[])
// longest(10, 20) -> Error! Numbers do not have a .length property
Combining keyof and extends
The keyof operator turns an object type’s property names into a union of literal strings.
For example, if type Book = { id: number; title: string }, then keyof Book is 'id' | 'title'.
Pairing keyof with extends lets you write functions that read a property from any object safely, without ever allowing a typo in the key name:
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
return items.map((item) => item[key])
}
const books = [
{ id: 1, title: 'JavaScript Handbook' },
{ id: 2, title: 'TypeScript Handbook' },
]
const titles = pluck(books, 'title') // inferred as string[]
const ids = pluck(books, 'id') // inferred as number[]
// pluck(books, 'titel') -> Compile error! 'titel' is not a key of Book
Let’s read those three pieces slowly:
Tis the object type in the array ({ id: number; title: string }).K extends keyof Trestrictskeyto'id' | 'title'.T[K][]looks up the type of propertyKonTand returns an array of it (string[]whenKis'title',number[]whenKis'id').
When to skip generics
Here is a rule of thumb that saves you from over-engineering: if a type parameter only appears once in a function signature, you probably do not need a generic.
Compare these two functions:
// Unnecessary generic: T only shows up once
function printLength<T extends { length: number }>(item: T): void {
console.log(item.length)
}
// Simpler and just as safe
function printLength(item: { length: number }): void {
console.log(item.length)
}
Use generics when you need to connect two types together (like an input type and a return type, or two parameters that must match). Otherwise, stick to plain types.
Everyday utility types and type transformations
Now that you understand generics and keyof, TypeScript’s built-in utility types will make immediate sense.
Instead of copying and tweaking an object type by hand every time you need an update payload or a public DTO, TypeScript ships with generic helpers that derive the new type from your original one.
| Utility type | What it produces | Common use |
|---|---|---|
Partial<T> | Makes every property of T optional | PATCH update payloads |
Required<T> | Makes every property of T required | Resolved config objects with defaults applied |
Readonly<T> | Makes every property of T read-only | Shared app constants |
Pick<T, K> | Keeps only keys K from T | Public user card (Pick<User, 'id' | 'name'>) |
Omit<T, K> | Drops keys K from T | Stripping passwordHash before returning JSON |
Record<K, V> | Object with keys K and values V | Lookup maps and counters |
ReturnType<F> | Extracts the return type of function F | Typing helper wrappers without repeating types |
Parameters<F> | Extracts parameter types of F as a tuple | Forwarding arguments to another function |
Awaited<T> | Unwraps a Promise<...> | Getting the resolved type of an async function |
Exclude<U, X> | Removes union members assignable to X | Dropping 'cancelled' from an order status union |
Extract<U, X> | Keeps only union members assignable to X | Selecting a subset of union branches |
NonNullable<T> | Removes null and undefined from T | Tightening nullable types after filtering |
Let’s see the four you will reach for every week, starting from one User type:
type User = {
id: number
name: string
email: string
passwordHash: string
}
// Safe to send to the browser: no passwordHash
type PublicUser = Omit<User, 'passwordHash'>
// Only the fields a profile header needs
type UserBadge = Pick<User, 'id' | 'name'>
// Allowed fields for an update form: all optional, and id cannot change
type UserUpdate = Partial<Omit<User, 'id' | 'passwordHash'>>
When you later add a bio: string field to User, PublicUser and UserUpdate pick it up automatically.
You can also derive types directly from an existing function using typeof + ReturnType + Awaited:
async function loadUser(id: number) {
return { id, name: 'Flavio', active: true }
}
type LoadedUser = Awaited<ReturnType<typeof loadUser>>
// { id: number; name: string; active: boolean }
Custom type predicates (is)
Earlier we saw how if (typeof x === 'string') narrows a value. When you extract a check into a reusable helper function, return a type predicate (value is Type) so TypeScript remembers the check outside the helper too:
function isDefined<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined
}
const rawTags: (string | undefined)[] = ['typescript', undefined, 'node']
const tags: string[] = rawTags.filter(isDefined)
Without value is T, calling isDefined inside .filter() returns a plain boolean, and older TypeScript setups keep undefined in the resulting array type. The predicate makes .filter(isDefined) narrow straight to string[].
Mapped types
Ever wondered how Partial<T> or Readonly<T> work inside TypeScript? They are written with mapped types, which loop over every key in keyof T:
type Nullable<T> = {
[K in keyof T]: T[K] | null
}
type DraftBook = Nullable<{ title: string; pages: number }>
// { title: string | null; pages: number | null }
You will not write mapped types every day, and that is fine. Knowing the [K in keyof T] syntax mostly helps you read library types without getting lost.
Template literal types
Just like JavaScript template strings combine strings at runtime, template literal types combine string literal unions at compile time:
type Entity = 'order' | 'invoice' | 'user'
type Action = 'created' | 'updated' | 'deleted'
type WebhookEvent = `${Entity}.${Action}`
// 'order.created' | 'order.updated' | 'order.deleted' | ... (9 valid strings)
Now typing 'order.creatd' fails immediately instead of silently missing a webhook handler.
One personal rule for all type transformations: if a type takes more than ten seconds for a teammate to read, break it into smaller named type aliases.
Classes, modules, and declaration files
Modern JavaScript projects use classes, ES modules, and third-party npm packages everywhere. Let’s see how TypeScript works with each of them.
Classes in TypeScript
TypeScript builds directly on standard JavaScript class syntax. Declare the types of your fields at the top of the class, and initialize them in the constructor:
class BankAccount {
readonly owner: string
#balance: number
constructor(owner: string, initialBalance = 0) {
this.owner = owner
this.#balance = initialBalance
}
deposit(amount: number): void {
if (amount <= 0) throw new Error('Amount must be positive')
this.#balance += amount
}
getBalance(): number {
return this.#balance
}
}
const account = new BankAccount('Flavio', 100)
account.deposit(50)
console.log(account.getBalance()) // 150
Notice I used JavaScript’s native #balance private field instead of TypeScript’s private balance keyword.
Why? Because #balance is enforced at runtime by JavaScript itself, and it works out of the box with Node.js native type stripping. TypeScript’s private keyword only exists during typechecking and disappears in the emitted JavaScript.
You can also tell TypeScript that a class follows a specific contract using implements:
interface StorageBackend {
get(key: string): string | undefined
set(key: string, value: string): void
}
class MemoryStorage implements StorageBackend {
#store = new Map<string, string>()
get(key: string): string | undefined {
return this.#store.get(key)
}
set(key: string, value: string): void {
this.#store.set(key, value)
}
}
If you forget to implement set or get its parameter type wrong, TypeScript flags MemoryStorage right on the class declaration.
ES Modules and import type
In TypeScript, you import and export functions, variables, and types using standard ES module syntax:
// src/user.ts
export type User = {
id: number
name: string
}
export function loadUser(id: number): User {
return { id, name: 'Flavio' }
}
When another file imports from src/user.ts, you can mark type-only imports with import type:
// src/app.ts
import type { User } from './user.ts'
import { loadUser } from './user.ts'
const current: User = loadUser(1)
Marking User with import type makes it crystal clear to both humans and tools (like Node.js type stripping, Vite, and esbuild) that the first line can be completely deleted when converting to JavaScript, while the second line must stay because loadUser runs at runtime.
Turning on "verbatimModuleSyntax": true in tsconfig.json enforces this automatically so you never run into mysterious runtime import errors.
Declaration files (.d.ts) and @types/* packages
When you install an npm package, how does TypeScript know the types of its functions if the package only ships compiled .js files?
Through declaration files ending in .d.ts. A .d.ts file contains only type definitions and no runtime code.
Most modern packages (like Zod, Astro, and Vitest) ship their own .d.ts files right inside the package, so autocomplete works immediately after npm install.
Older JavaScript libraries and runtime APIs like Node.js publish their types separately on npm under the @types/ scope, maintained by the community on DefinitelyTyped:
npm install -D @types/node
Install @types/* packages as dev dependencies (-D), because your app only needs them while editing and typechecking, never in production.
Asynchronous TypeScript and error handling
Almost every real JavaScript program fetches data, reads files, or queries a database asynchronously. Let’s make sure your async functions and try/catch blocks are cleanly typed.
Typing Promise<T> and async functions
An async function always returns a Promise. Wrap the resolved value type inside Promise<...>:
type Post = {
id: number
title: string
}
async function fetchPost(id: number): Promise<Post> {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
const data = (await response.json()) as Post
return data
}
(Hold onto that as Post line for a moment. In Chapter 13 we will replace that unsafe assertion with a real Zod schema check so bad network responses cannot sneak past it!)
When you run multiple promises in parallel with Promise.all(), TypeScript infers a tuple matching each promise’s resolved type:
async function loadDashboard() {
const [user, count] = await Promise.all([
Promise.resolve({ name: 'Flavio' }),
Promise.resolve(42),
])
// user is { name: string }, count is number
return `${user.name}: ${count}`
}
Promise.allSettled() returns a built-in discriminated union (status: 'fulfilled' with .value, or status: 'rejected' with .reason), so checking result.status === 'fulfilled' narrows cleanly without any extra types.
Why catch (error) is unknown
In JavaScript, anyone can throw anything: an Error instance, a plain string (throw 'oops'), or even null.
Under strict mode, TypeScript types the caught variable in catch (error) as unknown (controlled by useUnknownInCatchVariables, which strict: true enables). That stops you from crashing on error.message if a library threw a string instead of an Error.
Write a tiny helper once and reuse it across your project:
function getErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message
}
return String(error)
}
try {
JSON.parse('{bad json')
} catch (error) {
console.error('Parse failed:', getErrorMessage(error))
}
Returning typed results instead of throwing
For expected failures (like a missing record, an expired token, or invalid user input), throwing exceptions forces callers to remember try/catch because TypeScript does not track thrown error types in function signatures.
Returning a discriminated union makes failure part of the return type itself:
type Result<T> =
| { ok: true; data: T }
| { ok: false; error: string }
function parsePort(raw: string): Result<number> {
const value = Number(raw)
if (!Number.isInteger(value) || value < 1 || value > 65535) {
return { ok: false, error: `Invalid port: ${raw}` }
}
return { ok: true, data: value }
}
const port = parsePort('3000')
if (port.ok) {
console.log(`Listening on ${port.data}`)
} else {
console.error(port.error)
}
Callers physically cannot touch port.data without checking port.ok first.
Understanding tsconfig.json
tsconfig.json sits at the root of your project and tells TypeScript which files belong to the project, what JavaScript features exist in your runtime, and how strict the type checker should be.
When you run npx tsc --init, TypeScript generates a file with dozens of commented-out flags. You do not need to memorize all of them. I prefer a short config where every single line has a clear job.
One quick note on compiler versions: TypeScript 7 is the new Go-based compiler. It reads the same tsconfig.json as version 6 and runs much faster.
Some framework editor plugins (like Astro, Vue, or Svelte) still rely on the TypeScript 6 programmatic API, so install typescript@6 in those projects until their plugins switch over.
The compiler options that actually matter
| Option | Recommended value | What it does |
|---|---|---|
strict | true | Turns on the core safety checks (strictNullChecks, noImplicitAny, useUnknownInCatchVariables, and more) |
noUncheckedIndexedAccess | true | Treats items[0] and dict[key] as T | undefined instead of pretending the index always exists |
noEmit | true (apps) / false (libs) | Checks types without writing .js files when Vite, Astro, Node, or Bun runs your code |
target | "ES2022" or "ESNext" | Sets the JavaScript syntax version TypeScript emits and assumes the runtime supports |
lib | Usually omitted (follows target) | Controls built-in global types like DOM, ES2022, or WebWorker |
module | "ESNext" or "NodeNext" | Matches how your runtime or bundler loads modules |
moduleResolution | "bundler" or "nodenext" | Tells TypeScript how to find imported files and node_modules packages |
verbatimModuleSyntax | true | Keeps imports predictable and asks for import type on type-only imports |
isolatedModules | true | Ensures every file can be transpiled on its own (needed by Vite, esbuild, SWC, and Node) |
skipLibCheck | true | Skips typechecking inside node_modules/**/*.d.ts for faster checks |
types | ["node"] (on Node) | Lists global @types/* packages to load (empty by default since TypeScript 6) |
Why noUncheckedIndexedAccess is worth turning on
Even with "strict": true, TypeScript assumes tags[0] is always a string, even if tags is empty.
Turning on "noUncheckedIndexedAccess": true makes tags[0] have the type string | undefined, forcing you to check before calling .toUpperCase():
const tags = ['typescript', 'javascript']
const firstTag: string = tags[0] // Error TS2322 under noUncheckedIndexedAccess
Here is a real run of TypeScript 7.0.2 catching both our addShipping argument bug and that unsafe array lookup in one npx tsc --noEmit call:

Starter configs you can copy
For a browser app with Vite, Astro, or Next.js:
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["src"]
}
For a Node.js 22+ project running .ts files directly or compiling with tsc:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "nodenext",
"strict": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
Notice "erasableSyntaxOnly": true in the Node.js config. It warns you if you accidentally use TypeScript features like enum or parameter properties that Node’s built-in type stripping cannot erase.
Path aliases, include, and extends
Three more config keys show up in almost every project:
includeandexcludecontrol which files TypeScript checks ("include": ["src"],"exclude": ["dist", "coverage"]).pathscreates clean import aliases so you can writeimport { Button } from '@/components/Button'instead of../../../components/Button:
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
Just remember that paths does not rewrite emitted JavaScript imports, so configure the same alias in Vite or your bundler too.
extendsinherits settings from a shared base config (like"extends": "astro/tsconfigs/strict").
When you are unsure what settings TypeScript actually resolved after inheritance, run:
npx tsc --showConfig
Fixing two classic tsconfig.json errors
Cannot find type definition file for 'node'
Your config lists "types": ["node"] (or uses Node globals like process), and @types/node is not installed. Run:
npm install -D @types/node
Then restart your editor’s TypeScript server (in VS Code, open the Command Palette and run TypeScript: Restart TS Server).
No inputs were found in config file
TypeScript found tsconfig.json, looked in the folders listed in include, and found zero .ts or .tsx files. Either add your first .ts file inside src/, or point "include": ["./src/**/*.ts"] at the folder where your TypeScript files live.
Runtime validation at boundaries with Zod
We mentioned this in Chapter 1, and now it is time to solve it properly.
TypeScript protects every function call inside your codebase. The moment data crosses an external boundary (an HTTP API response, a form submission, a webhook payload, or process.env), TypeScript cannot check it because all your types disappeared before the code ran.
If you write const user = (await response.json()) as User, TypeScript nods politely and lets anything through. If the API changed name to fullName or returned { error: 'Rate limited' }, your app crashes later with Cannot read properties of undefined.
The clean solution is to validate untrusted inputs at the boundary with a schema library like Zod, and let Zod generate the TypeScript type for you from that same schema.
Installing Zod and creating your first schema
Install Zod (this guide uses Zod 4):
npm install zod
Import z and define a schema describing the exact shape you expect:
import { z } from 'zod'
const OrderSchema = z.object({
email: z.email(),
totalCents: z.number().int().nonnegative(),
role: z.enum(['member', 'admin']).default('member'),
})
Now derive the TypeScript type straight from OrderSchema using z.infer:
type Order = z.infer<typeof OrderSchema>
// { email: string; totalCents: number; role: 'member' | 'admin' }
You maintain one definition. If you add a couponCode: z.string().optional() field to the schema, both runtime validation and the TypeScript Order type update together.
parse() vs safeParse()
Zod gives you two ways to validate incoming data:
OrderSchema.parse(input)returns the typedOrderif valid, or throws aZodErrorif invalid. Use it when a failure should abort the current operation (like loading required environment variables at startup).OrderSchema.safeParse(input)never throws. It returns a discriminated union:{ success: true, data: Order }or{ success: false, error: ZodError }. Use it for form submissions and HTTP request handlers where you want to show friendly validation errors.
Let’s run a real check with both valid and invalid data:
const good = OrderSchema.safeParse({
email: 'flavio@flaviocopes.com',
totalCents: 2900,
})
if (good.success) {
console.log('Valid order:', good.data)
}
const bad = OrderSchema.safeParse({
email: 'not-an-email',
totalCents: -50,
})
if (!bad.success) {
console.log(
'Invalid issues:',
bad.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
)
}
Here is tsc --noEmit passing and Node 22 running that exact file with Zod 4.6.7:

Notice two neat things in that output: Zod filled in role: 'member' automatically from .default('member'), and when the input was bad, it returned exact per-field error messages instead of crashing.
Validating a fetch() API response
Remember our fetchPost function from Chapter 11 where we temporarily used as Post? Here is the rock-solid version:
import { z } from 'zod'
const PostSchema = z.object({
id: z.number().int().positive(),
title: z.string().min(1),
body: z.string(),
})
type Post = z.infer<typeof PostSchema>
async function fetchPost(id: number): Promise<Post> {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`)
}
const raw: unknown = await response.json()
return PostSchema.parse(raw)
}
Marking raw as unknown is deliberate. The network payload has not earned the Post type until PostSchema.parse(raw) verifies every field.
Reusing schemas and custom rules
Just like TypeScript’s Pick, Omit, and Partial, Zod lets you derive new schemas from existing ones:
const UserSchema = z.object({
id: z.uuid(),
name: z.string().min(1),
email: z.email(),
age: z.number().int().nonnegative().optional(),
})
const CreateUserSchema = UserSchema.omit({ id: true })
const UpdateUserSchema = CreateUserSchema.partial()
And when you need a cross-field rule (like confirming two password inputs match), add .refine():
const PasswordForm = z
.object({
password: z.string().min(8),
confirmPassword: z.string(),
})
.refine((data) => data.password === data.confirmPassword, {
message: 'Passwords must match',
path: ['confirmPassword'],
})
For the full schema API, check the official Zod documentation.
Reading and fixing common TypeScript errors
TypeScript errors can look scary when a nested object fails to match and the compiler prints ten lines of text.
Here is the trick that makes them immediately readable: start from the bottom line of the error message, not the top.
Look at an error like this:
error TS2322: Type '{ user: { id: number; name: string | undefined } }' is not assignable to type 'DashboardProps'.
Types of property 'user' are incompatible.
Type '{ id: number; name: string | undefined }' is not assignable to type 'User'.
Types of property 'name' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
The top five lines just trace the outer wrapper objects. The last line tells you the exact bug in nine words: name can be undefined, and User expects a string.
Here are the error codes you will run into most often and how to fix each one fast:
| Code | What TypeScript means | Fast fix |
|---|---|---|
TS2322 | Type A is not assignable to type B | Read the bottom line: usually undefined under strict, or a typo in a string literal |
TS2345 | Function argument does not match the parameter type | Pass the expected type, or narrow the variable before calling the function |
TS18048 | Value is possibly undefined | Guard with if (!value) return, optional chaining (value?.prop), or ?? |
TS2339 | Property does not exist on type | Check for a typo, narrow the union first, or validate unknown with Zod |
TS7006 | Parameter implicitly has an any type | Add an explicit type annotation on the function parameter |
TS2307 | Cannot find module '...' or its type declarations | Check the file path/extension, or install @types/<package> |
TS1295 | ESM syntax in a CommonJS file under verbatimModuleSyntax | Add "type": "module" to package.json |
TS6133 | Variable is declared but never read | Delete the unused variable, or prefix an intentionally unused parameter with _ |
Migrating a JavaScript project to TypeScript
If you already have a working JavaScript project, never pause feature work for three weeks to rewrite every file at once. TypeScript was designed from day one for gradual adoption.
Follow these four steps at your own pace:
- Add
tsconfig.jsonwith"allowJs": trueand"strict": true. Your existing.jsfiles keep working untouched while every new.tsfile gets strict checking. - Start with leaf utility files. Pick small helper files that do not import much else (date formatters, price calculators, string helpers), rename them from
.jsto.ts, and add parameter types. - Protect your boundaries with Zod. Type the shapes coming out of your API calls, database queries, and forms first. That gives you the biggest bug-catching return right away.
- Gate pull requests in CI. Add
npx tsc --noEmitto your test script or GitHub Actions workflow so new type errors never slip back in.
If you want a gentler first step before renaming files to .ts, you can even add // @ts-check at the top of a plain .js file and annotate parameters with JSDoc comments (/** @param {number} price */). Your editor will run TypeScript’s checker on that .js file immediately.
Building and publishing a TypeScript library
Once you write a handy set of TypeScript helpers that you want to share across projects or publish to npm, you need to ship compiled JavaScript (ESM and optionally CommonJS) plus .d.ts declaration files so consumers get full autocomplete.
My favorite tool for this is tsdown (built on Rolldown), paired with Vitest for tests.
Create the package folder and install your dev tools:
mkdir tiny-duration
cd tiny-duration
npm init -y
npm pkg set type=module
npm install -D typescript tsdown vitest
Write your library in src/index.ts:
export type FormatDurationOptions = {
compact?: boolean
}
export function formatDuration(
milliseconds: number,
options: FormatDurationOptions = {},
): string {
if (!Number.isFinite(milliseconds) || milliseconds < 0) {
throw new TypeError('milliseconds must be a non-negative number')
}
const totalSeconds = Math.floor(milliseconds / 1000)
const minutes = Math.floor(totalSeconds / 60)
const seconds = totalSeconds % 60
if (options.compact) {
return `${minutes}:${String(seconds).padStart(2, '0')}`
}
const parts: string[] = []
if (minutes > 0) parts.push(`${minutes}m`)
if (seconds > 0 || parts.length === 0) parts.push(`${seconds}s`)
return parts.join(' ')
}
Configure tsdown.config.ts to emit ESM, CommonJS, and .d.ts files together:
import { defineConfig } from 'tsdown'
export default defineConfig({
entry: ['src/index.ts'],
format: ['esm', 'cjs'],
dts: true,
clean: true,
sourcemap: true,
})
Point package.json at the built files and wire up a prepack safety gate so you can never publish broken types or failing tests:
{
"name": "tiny-duration",
"version": "1.0.0",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"files": ["dist"],
"scripts": {
"build": "tsdown",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"prepack": "npm run typecheck && npm run test && npm run build"
}
}
Add a small test in src/index.test.ts:
import { describe, expect, test } from 'vitest'
import { formatDuration } from './index.ts'
describe('formatDuration', () => {
test('formats minutes and seconds', () => {
expect(formatDuration(90_500)).toBe('1m 30s')
})
test('supports compact output', () => {
expect(formatDuration(90_500, { compact: true })).toBe('1:30')
})
test('rejects negative values', () => {
expect(() => formatDuration(-1)).toThrow(TypeError)
})
})
Before running npm publish, always inspect what will actually go into the package:
npm pack --dry-run
Make sure dist/index.mjs, dist/index.cjs, dist/index.d.mts, dist/index.d.cts, package.json, and README.md are all listed, and no test files or local scratch notes snuck in.
Where to go from here
You now know every piece of TypeScript you need to build real web apps, backend services, and libraries with confidence.
The fastest way to make TypeScript feel natural is to use it on your next small project with "strict": true from day one. Lean on type inference, model app state with discriminated unions, validate external data with Zod, and keep your types boring and readable.
If you want to keep exploring, check out my free JavaScript Handbook, Node.js Handbook, and the interactive TypeScript Utility Types reference and tsconfig.json generator on flaviocopes.com.
TypeScript Utility Types Explorer
Explore Partial, Pick, Omit, Record, ReturnType, and friends with before/after examples and when to use each.
Want me to talk about your product? You can sponsor this site.
Related posts about typescript: