Write type-safe JavaScript with TypeScript. A complete guide covering the type system, type narrowing, generics, utility types, and practical patterns.
Beginner
Updated Oct 1, 2026
~3 min read
8 sections
4 code examples
Web IDE lab included
π·
TypeScript Web IDE
Run code in the browser with nothing to install and learn through step-by-step examples.
Write type-safe JavaScript with TypeScript. A complete guide covering the type system, type narrowing, generics, utility types, and practical patterns. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.
Key perspective
Frontend / app development
Do not stop at drawing the screen: look at state, data requests, routing, accessibility, and the unit of deployment together.
To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning TypeScript.
Learning flow
Rendering diagramβ¦
Architecture view
Rendering diagramβ¦
Project setup
When you first open TypeScript, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.
Only a few values in the tsconfig.json generated by tsc --init are ones you actually touch often. It is best to always leave strict on, and set moduleResolution to bundler if you use a modern bundler such as Vite/esbuild.
Here you look at The type system alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
A discriminated union is a pattern that puts a shared literal field (ok here) on each type, so that checking just that value lets TypeScript narrow the types of the remaining fields automatically. With this pattern, the mistake of "accessing the error field after success" is caught at compile time.
TYPESCRIPT
// Discriminated Union (recommended pattern)type Result<T> = | { ok: true; value: T } | { ok: false; error: string };function parse(input: string): Result<number> { const n = Number(input); return isNaN(n) ? { ok: false, error: `"${input}" is not a number` } : { ok: true, value: n };}const result = parse("42");if (result.ok) console.log(result.value); // TypeScript narrows the type
Type narrowing
Here you look at Type narrowing alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
A value declared with a union type (A | B) cannot by itself be known to be A or B. Checking a condition with typeof, instanceof, in, or a type guard function you write yourself lets TypeScript narrow the actual type inside that branch, so you can safely access the members of that type.
narrowing.tsTYPESCRIPT
type Circle = { kind: 'circle'; radius: number };type Square = { kind: 'square'; side: number };type Shape = Circle | Square;function area(shape: Shape): number { // Branching on the 'kind' field narrows the type automatically inside each block if (shape.kind === 'circle') { return Math.PI * shape.radius ** 2; // shape is narrowed to Circle here } return shape.side ** 2; // narrowed to Square here}// Custom type guard β the is keyword pins down the typefunction isCircle(shape: Shape): shape is Circle { return shape.kind === 'circle';}
Generics
Here you look at Generics alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
A generic is a placeholder where "the type is not decided now but filled in at the point the function or class is used". Adding a constraint such as `` narrows it from a completely free type to a meaningful range such as "one of the actual keys of T".
TYPESCRIPT
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> { return Object.fromEntries(keys.map(k => [k, obj[k]])) as Pick<T, K>;}// Conditional typestype NonNullable<T> = T extends null | undefined ? never : T;type ReturnType<T extends (...args: unknown[]) => unknown> = T extends (...args: unknown[]) => infer R ? R : never;// Builder patternclass QueryBuilder<T> { private filters: Partial<T> = {}; where<K extends keyof T>(key: K, value: T[K]): this { this.filters[key] = value; return this; } build(): Partial<T> { return this.filters; }}
Utility types
Utility types is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
The utility types built into TypeScript let you transform and reuse types you have already defined instead of rewriting them by hand each time. For example, if you have a User type with every field required at creation, an edit form can use Partial to get a version where "sending only some fields is fine" without defining it separately.
Type
Description
Example
Partial
Makes every property optional
Partial
Required
Makes every property required
Required
Pick
Selects only specific properties
Pick
Omit
Excludes specific properties
Omit
Record
A key-value map type
Record
TypeScript practical design
TypeScript practical design is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
With TypeScript, getting the boundary types exactly right matters more than writing many types. Narrow unknown input with a schema and separate domain types from DTOs.
Decision point
Question to ask
Practical guideline
Boundaries
Which parts of the TypeScript code are most likely to change?
Separate input/output, configuration, external integrations, and the core rules.
State
Where is state created and where does it go away?
Make the owner and lifecycle of state visible in the code.
Failure
What does the caller receive on failure?
Decide the timeout, fallback, and error contract first.
TypeScript operating standards
This section covers TypeScript operating standards from a practical perspective. Instead of memorizing the concept, focus on the situations in which you would reach for it.
TypeScript verification strategy is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
Use type tests, runtime validation, and API type regression checks together.
Quality axis
How to verify
Definition of done
Correctness
Automate the normal/failure cases.
The core scenarios pass reproducibly.
Regression prevention
When fixing a bug, leave the same case behind as a test.
The same failure is not deployed again.
Operability
Check the logs, metrics, and alerts.
There is a path for tracing the cause when a problem occurs.
TypeScript: frequently asked questions
Do I have to use TypeScript?
For code that several people maintain for a long time, it is recommended. The shape of function inputs and outputs is visible in the code, wrong values and typos are caught before running, and editor autocomplete and renaming become accurate. For short scripts and experiments, JavaScript can be simpler.
What is the difference between any and unknown?
any turns type checking off and allows any operation, while unknown can hold anything but cannot be used until its type is checked. For values whose type you do not know, such as input from outside, receive them as unknown and check before use.
When do I use interface and when type?
Both can define the shape of an object, and the difference is small. Unions, tuples, and types composed from other types can only be expressed with type, and an interface can be extended by declaring it again under the same name. What matters is that the team picks one convention and applies it consistently.