The TypeScript Guide

By

Published · Updated

Tagged: TypeScript

Learn TypeScript from scratch: setup, inference, primitives, objects, unions, functions, generics, type narrowing, tsconfig.json, and runtime validation.

TypeScript is JavaScript with a static type checker on top. You write code that looks almost identical to JavaScript, and the compiler catches typos, missing properties, and mismatched arguments before your program runs.

Browsers and Node.js still run JavaScript at the end. TypeScript checks your types while you edit and build, then erases them from the output.

Install and run TypeScript

Install TypeScript as a local dev dependency so everyone on the project runs the same compiler version:

npm init -y
npm install --save-dev typescript
npx tsc --init

Create a small file called index.ts:

const greeting: string = 'Hello'
console.log(greeting.toUpperCase())

Run npx tsc --noEmit to type-check the whole project without writing output files. That is the command I run in editors and CI when a bundler like Vite or Astro handles the final build.

Let TypeScript infer obvious types

TypeScript sees const name = 'Ada' and already knows name is a string. Writing const name: string = 'Ada' just repeats what the compiler knows.

Add annotations where they carry real information: function parameters, public APIs, empty arrays, and variables initialized later.

let score: number
score = 42

const names: string[] = ['Ada', 'Lin']
const point: [number, number] = [10, 20]

Use lowercase string, number, and boolean for primitives. Avoid any because it turns the checker off. When you genuinely do not know a value’s shape yet, use unknown, then check it before calling methods on it.

Handle null and undefined explicitly

Turn on "strict": true in tsconfig.json from day one. Under strict mode, a value that might be missing has to say so in its type:

function uppercase(value: string | undefined) {
  if (value === undefined) return ''
  return value.toUpperCase()
}

Once you check value === undefined, TypeScript narrows value to string on the next line. Avoid forcing the compiler with ! or as unless you have real proof the value is there.

Objects, unions, and intersections

Describe object shapes with a type alias or an interface. Mark optional fields with ? and immutable fields with readonly:

type User = {
  readonly id: number
  name: string
  nickname?: string
}

const user: User = { id: 1, name: 'Ada' }

Use union types (|) when a value can be one of several shapes, and literal unions to lock down a small set of allowed strings:

type Status = 'idle' | 'loading' | 'success' | 'error'

Now 'laoding' becomes a compile error instead of a silent bug. See TypeScript type for a string or array of strings for more union examples.

Combine object requirements with an intersection (&):

type Timestamped = { createdAt: Date }
type SavedUser = User & Timestamped

Functions and generics

Annotate parameters at the function boundary and let TypeScript infer simple return types. Add an explicit return type on exported functions so you do not accidentally break callers:

function greet(name: string, times = 1): string {
  return name.repeat(times)
}

function transform(value: string, fn: (input: string) => string): string {
  return fn(value)
}

For destructured object parameters, type the object after the destructuring pattern. I wrote a short guide on object destructuring with types in TypeScript because that syntax trips up almost everyone coming from JavaScript.

Use generics when a function needs to connect an input type to its return type without throwing the specific type away:

function first<T>(items: T[]): T | undefined {
  return items[0]
}

const lead = first(['Ada', 'Grace']) // string | undefined

Add extends when the generic needs a specific property:

items: readonly T[]pluck<T, K extendskeyof T>(items, key)key: K ('title')Returns T[K][](string[])Compile error oninvalid key
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b
}

If a type parameter only appears once, you usually do not need a generic at all.

Mapped types and template literal types

Built-in utility types like Partial<T>, Pick<T, K>, and Omit<T, K> are all written using mapped types ([K in keyof T]). You can write your own when you want derived types to stay in sync automatically:

type Flags<T> = {
  [K in keyof T]: boolean
}

type EventName = `on${Capitalize<'click' | 'focus' | 'blur'>}`
// 'onClick' | 'onFocus' | 'onBlur'

Template literal types pair well with discriminated unions to type route paths, CSS tokens, or event names without repeating string literals by hand.

Narrowing and discriminated unions

Narrowing is how you turn a broad union into a specific type using normal JavaScript checks:

My favorite pattern for app state and API responses is a discriminated union, where every variant shares one literal field like status:

Zod safeParse()status ==='loading'status ==='success'status ==='error'defaultunknown APIpayloadFetchStateUnionLoading branchAccessstate.datasafelyAccessstate.messagesafelyconst _x: never= state(Compile-timeexhaustiveness)
type Result =
  | { status: 'success'; data: string }
  | { status: 'error'; message: string }

function render(result: Result) {
  if (result.status === 'success') {
    return result.data
  }
  return result.message
}

Inside the if, TypeScript knows result.data exists. Outside it, TypeScript knows result.message exists.

When you need a reusable check, write a type predicate (value is User):

function isString(value: unknown): value is string {
  return typeof value === 'string'
}

tsconfig.json and declaration files

Keep one tsconfig.json at the root of your repo so your editor, CLI, and CI agree on the rules:

{
  "compilerOptions": {
    "strict": true,
    "noEmit": true,
    "moduleResolution": "bundler",
    "target": "ES2022"
  }
}

You can generate a tailored config with my tsconfig.json generator.

Libraries ship .d.ts declaration files that describe their JavaScript exports to TypeScript. Most modern packages include their own types. For older JavaScript libraries without built-in types, install the matching @types/<package> package as a dev dependency.

Types disappear at runtime

This is the single most important mental model in TypeScript: types do not validate data at runtime.

tsc --noEmitZod safeParse()TypeScript Source(.ts)Compile-time TypeCheck(catches TS2322,TS18048)Untrusted JSON InputRuntime Validation-> typed Order(z.infer)
const user = (await response.json()) as User

That as User tells TypeScript to trust you. It does not inspect the JSON coming off the network. If the server returns something else, your code crashes in production.

Keep uncertain inputs (API responses, form data, environment variables, JSON files) as unknown at the boundary and parse them with a runtime validator like Zod. Once parsed, TypeScript carries the trusted type through the rest of your code.

Migrating an existing JavaScript project gradually

You do not need to rewrite a working JavaScript codebase in one weekend. Add TypeScript incrementally:

1. Add tsconfig.jsonallowJs: true,strict: true2. Convert leafutils.js -> .ts3. Add Zod schemasat HTTP / DBboundaries4. Gate PRs in CItsc --noEmit

Start with shared utility modules that have no dependencies, then work outward to routes and UI components. On Node.js 22+, you can even run .ts scripts directly with built-in type stripping without a separate build step.

Fixing common problems and going deeper

You can browse everything I wrote about TypeScript in the typescript tag.

Want me to talk about your product? You can sponsor this site.

Related posts about typescript: