TypeScript
The type system and the toolchain around it — everyday types, typing functions, structural typing, narrowing, generics, type-level programming, classes and decorators, modules and declaration files, and the practice of running TypeScript in a real codebase. The JavaScript language itself is taught in `javascript`; framework usage lives in `angular` and `react`. Sixty-four lessons.
Why TypeScript, and what a type checker doesThe bugs plain JavaScript only reports at runtime, how a static type checker catches them early, and why every type disappears before your code runs.Installing TypeScript and your first compileInstall TypeScript per project, compile a file with tsc, read the emitted JavaScript, and use --init, --watch, and --noEmit.tsconfig explainedWhat the core tsconfig.json options control — target, lib, module, include, outDir, noEmit — and how to pick values for a real project.Strict mode and the compiler flags that matterWhat the strict flag turns on, the extra checks it leaves off like noUncheckedIndexedAccess, and which ones are worth enabling in a new project.Running TypeScript without a build stepHow Node's built-in type stripping, erasableSyntaxOnly, tsx, and ts-node let you run .ts files directly, and what each one skips.The editor and the TypeScript language serverHow the TypeScript language server powers hovers, quick fixes, and refactors in your editor, and what the Go-native TypeScript 7 compiler changes.Primitive typesThe seven primitive types TypeScript checks, why they are written lowercase, and what the compiler rejects once a value has one.Type annotations and type inferenceHow TypeScript works out most types from your values, where you still need to write an annotation, and why fewer annotations is usually better.Arrays and tuplesTyping lists of any length with `T[]`, and fixed-position data with tuples: named, optional, and rest elements, and why tuples need annotating.Object types, optional and readonly propertiesDescribing the shape of an object, marking properties that may be absent with `?`, and properties that must not be reassigned with `readonly`.Readonly and immutabilityRead-only arrays and tuples, `Readonly<T>`, and `as const`: how TypeScript stops mutation at compile time, and where that protection ends.any, unknown, never, and voidThe four special types: `any` switches checking off, `unknown` is the safe top type, `never` is the empty type, and `void` means no useful return.Null, undefined, and strict null checksHow `strictNullChecks` turns null and undefined into types you must handle, and how to model missing values with `T | null`, `?`, and `??`.Union and literal typesCombining types with `|`, using exact values like `"GET"` as types, and the widening rules that decide when TypeScript keeps a literal.Enums and their alternativesHow `enum` and `const enum` work, why they are not erasable syntax, and when an `as const` object with a derived union is the better choice.Parameter and return typesWhy TypeScript needs you to annotate parameters but can usually work out return types itself, and when writing the return type anyway pays off.Optional, default, and rest parametersTyping parameters callers may leave out, parameters with fallback values, and functions that take any number of arguments.Function type expressions and call signaturesDescribing the type of a function itself, from the arrow syntax to call signatures for functions with properties and construct signatures for classes.Function overloadsGiving one function several call signatures so its return type can follow its arguments, and knowing when a union or optional parameter is the simpler answer.Typing this and callbacksDeclaring what `this` must be with a fake first parameter, and typing callbacks, including why a void callback type accepts a function that returns a value.Type aliases vs interfacesTwo ways to name a type: what `type` can express that `interface` can't, where interfaces behave differently, and how to choose between them.Extending interfaces and intersection typesBuilding bigger types from smaller ones with `interface extends` and the `&` operator, how each handles conflicts, and why `extends` is cheaper.Declaration mergingHow TypeScript combines declarations that share a name: interfaces, namespaces, functions, classes and enums, and why type aliases can't merge.Structural typing and excess property checksTypeScript compares types by shape, not by name. Why that fits JavaScript, and the one place it gets stricter: extra properties on fresh object literals.Index signatures and RecordTyping objects used as dictionaries: index signature syntax and its rules, what reading a missing key returns, and when `Record<K, V>` says it better.Type compatibility and varianceWhen one type can stand in for another: covariance, contravariance, why methods stay bivariant under strictFunctionTypes, and the in/out annotations.Control flow analysis and narrowingHow the checker follows if, return, and assignment to give a variable a narrower type on each line, using truthiness and equality checks.typeof, instanceof, and in narrowingWhat the type checker does with typeof, instanceof, and in checks, and where each one narrows less than you might expect.Discriminated unionsModelling data that comes in several shapes as a union of object types sharing a literal tag, so one check narrows the whole object.Exhaustiveness checking with neverUsing the never type to make the compiler flag every switch that forgets a union member, including ones added long after the code was written.Type guards and assertion functionsMoving narrowing checks into reusable functions with `x is T` predicates and `asserts` signatures, and what TypeScript 5.5 now infers for you.Type assertions, non-null, and satisfiesOverriding the checker with `as` and `!` when you know more than it does, and checking a value with `satisfies` without losing its precise type.Why generics, and generic functionsThe problem `any` and `unknown` can't solve, and how a type parameter lets one function keep the link between what goes in and what comes out.Generic constraintsUsing `extends` to require a minimum shape from a type parameter, so a generic function can use that shape and still return the caller's exact type.Generic defaults and const type parametersDefault type arguments that keep generic types short to use, and `const` type parameters that infer literal types without callers writing `as const`.Generic interfaces, type aliases, and classesPutting type parameters on interfaces, type aliases, and classes, so reusable shapes like `Result<T>` and `Queue<T>` keep their contents typed.How type argument inference worksHow TypeScript picks type arguments from a call's inference sites, why callbacks are inferred last, and how `NoInfer` stops an argument from widening `T`.The keyof and typeof type operatorsDeriving types from what already exists: keyof for a type's keys, type-level typeof for a value's type, and keyof typeof to get keys from a runtime object.Indexed access typesLooking up a property's type with T[K]: nested lookups, unions of keys, T[keyof T], T[number] for arrays, and the typeof arr[number] pattern.Utility types for objectsPartial, Required, Readonly, Pick, Omit and Record: deriving update payloads, public views and lookup tables from one model instead of copying it.Utility types for unions and functionsExclude, Extract and NonNullable for filtering unions; ReturnType, Parameters and Awaited for reading function types; NoInfer for steering inference.Mapped typesBuilding an object type by looping over keys: T[K] for property types, adding and removing readonly and ?, modifier preservation, and key remapping with as.Conditional typesChoosing between two types with `T extends U ? X : Y`, so a type can branch on its input the way an expression branches on a value.The infer keywordDeclaring a type variable inside a conditional's `extends` clause so TypeScript fills it in, to pull element, return and promise types out of other types.Distributive conditional typesWhy a conditional type applied to a union runs once per member, how `[T] extends [U]` turns that off, and why `never` in gives `never` out.Template literal typesBuilding string types with backtick syntax, generating unions from combinations, and pulling strings apart with `infer`.Recursive typesTypes that refer to themselves: JSON values and trees, deep transformations like DeepReadonly, the instantiation depth limit, and tail recursion.Classes and access modifiersWhat TypeScript adds to JavaScript classes: field declarations, public/private/protected, private vs #private, parameter properties, and override.Abstract classes and implementing interfacesChecking a class against an interface with implements, sharing code through abstract classes, and how to choose between the two.DecoratorsTypeScript 5's standard decorators, the (value, context) signature, field and accessor decorators, and how legacy experimentalDecorators differs.Modules and type-only importsHow TypeScript decides which imports survive compilation, and how import type, isolatedModules, and verbatimModuleSyntax make that explicit.Module resolutionHow TypeScript finds the file behind an import under nodenext and bundler, why extensions and exports matter, and what paths does and doesn't do.Namespaces: the legacy module systemWhy TypeScript has namespaces, what they compile to, why ES modules replaced them, and where they still appear in global declaration files.Declaration files and DefinitelyTypedWhat .d.ts files are, where a package's types come from, how @types packages are found through types and typeRoots, and what skipLibCheck skips.Writing declaration files and module augmentationTyping an untyped package with declare module, then extending a library's or the global scope's types with module augmentation and declare global.Typing asynchronous codeHow TypeScript types promises and async functions: Promise<T>, Awaited<T>, Promise.all tuples, unknown in catch, and the floating promises tsc misses.Branded types and nominal typingWhy two string IDs are interchangeable in TypeScript, and how a brand makes UserId and OrderId distinct types with no runtime cost.Validating untrusted data at runtimeTypes vanish at runtime, so API responses and form input need a real check. Schema libraries like Zod and Valibot validate data and infer the type.Reading and debugging type errorsHow to read a long TypeScript error from the bottom up, inspect what the checker inferred, and corner a confusing error until it points at the real line.Testing your typesRuntime tests can't see a wrong type. Type tests can: @ts-expect-error for code that must fail, expectTypeOf in Vitest or expect-type, and tsd.Linting with typescript-eslintSet up typescript-eslint with flat config and typed linting, and catch the async and any-related bugs that tsc lets through.Migrating a JavaScript codebase to TypeScriptMove a JavaScript project to TypeScript gradually with allowJs, checkJs, JSDoc types, and strictness you tighten one file or one flag at a time.Project references and monoreposSplit a large TypeScript repo into composite projects linked with references, build them with tsc --build, and know when workspace packages suffice.Publishing a typed libraryShip declaration files with your package, wire them up through package.json exports with types first, and check the result with Are the Types Wrong.
Why TypeScript, and the toolchain
- Why TypeScript, and what a type checker doesThe bugs plain JavaScript only reports at runtime, how a static type checker catches them early, and why every type disappears before your code runs.
- Installing TypeScript and your first compileInstall TypeScript per project, compile a file with tsc, read the emitted JavaScript, and use --init, --watch, and --noEmit.
- tsconfig explainedWhat the core tsconfig.json options control — target, lib, module, include, outDir, noEmit — and how to pick values for a real project.
- Strict mode and the compiler flags that matterWhat the strict flag turns on, the extra checks it leaves off like noUncheckedIndexedAccess, and which ones are worth enabling in a new project.
- Running TypeScript without a build stepHow Node's built-in type stripping, erasableSyntaxOnly, tsx, and ts-node let you run .ts files directly, and what each one skips.
- The editor and the TypeScript language serverHow the TypeScript language server powers hovers, quick fixes, and refactors in your editor, and what the Go-native TypeScript 7 compiler changes.
Everyday types
- Primitive typesThe seven primitive types TypeScript checks, why they are written lowercase, and what the compiler rejects once a value has one.
- Type annotations and type inferenceHow TypeScript works out most types from your values, where you still need to write an annotation, and why fewer annotations is usually better.
- Arrays and tuplesTyping lists of any length with `T[]`, and fixed-position data with tuples: named, optional, and rest elements, and why tuples need annotating.
- Object types, optional and readonly propertiesDescribing the shape of an object, marking properties that may be absent with `?`, and properties that must not be reassigned with `readonly`.
- Readonly and immutabilityRead-only arrays and tuples, `Readonly<T>`, and `as const`: how TypeScript stops mutation at compile time, and where that protection ends.
- any, unknown, never, and voidThe four special types: `any` switches checking off, `unknown` is the safe top type, `never` is the empty type, and `void` means no useful return.
- Null, undefined, and strict null checksHow `strictNullChecks` turns null and undefined into types you must handle, and how to model missing values with `T | null`, `?`, and `??`.
- Union and literal typesCombining types with `|`, using exact values like `"GET"` as types, and the widening rules that decide when TypeScript keeps a literal.
- Enums and their alternativesHow `enum` and `const enum` work, why they are not erasable syntax, and when an `as const` object with a derived union is the better choice.
Typing functions
- Parameter and return typesWhy TypeScript needs you to annotate parameters but can usually work out return types itself, and when writing the return type anyway pays off.
- Optional, default, and rest parametersTyping parameters callers may leave out, parameters with fallback values, and functions that take any number of arguments.
- Function type expressions and call signaturesDescribing the type of a function itself, from the arrow syntax to call signatures for functions with properties and construct signatures for classes.
- Function overloadsGiving one function several call signatures so its return type can follow its arguments, and knowing when a union or optional parameter is the simpler answer.
- Typing this and callbacksDeclaring what `this` must be with a fake first parameter, and typing callbacks, including why a void callback type accepts a function that returns a value.
Shaping data
- Type aliases vs interfacesTwo ways to name a type: what `type` can express that `interface` can't, where interfaces behave differently, and how to choose between them.
- Extending interfaces and intersection typesBuilding bigger types from smaller ones with `interface extends` and the `&` operator, how each handles conflicts, and why `extends` is cheaper.
- Declaration mergingHow TypeScript combines declarations that share a name: interfaces, namespaces, functions, classes and enums, and why type aliases can't merge.
- Structural typing and excess property checksTypeScript compares types by shape, not by name. Why that fits JavaScript, and the one place it gets stricter: extra properties on fresh object literals.
- Index signatures and RecordTyping objects used as dictionaries: index signature syntax and its rules, what reading a missing key returns, and when `Record<K, V>` says it better.
- Type compatibility and varianceWhen one type can stand in for another: covariance, contravariance, why methods stay bivariant under strictFunctionTypes, and the in/out annotations.
Narrowing
- Control flow analysis and narrowingHow the checker follows if, return, and assignment to give a variable a narrower type on each line, using truthiness and equality checks.
- typeof, instanceof, and in narrowingWhat the type checker does with typeof, instanceof, and in checks, and where each one narrows less than you might expect.
- Discriminated unionsModelling data that comes in several shapes as a union of object types sharing a literal tag, so one check narrows the whole object.
- Exhaustiveness checking with neverUsing the never type to make the compiler flag every switch that forgets a union member, including ones added long after the code was written.
- Type guards and assertion functionsMoving narrowing checks into reusable functions with `x is T` predicates and `asserts` signatures, and what TypeScript 5.5 now infers for you.
- Type assertions, non-null, and satisfiesOverriding the checker with `as` and `!` when you know more than it does, and checking a value with `satisfies` without losing its precise type.
Generics
- Why generics, and generic functionsThe problem `any` and `unknown` can't solve, and how a type parameter lets one function keep the link between what goes in and what comes out.
- Generic constraintsUsing `extends` to require a minimum shape from a type parameter, so a generic function can use that shape and still return the caller's exact type.
- Generic defaults and const type parametersDefault type arguments that keep generic types short to use, and `const` type parameters that infer literal types without callers writing `as const`.
- Generic interfaces, type aliases, and classesPutting type parameters on interfaces, type aliases, and classes, so reusable shapes like `Result<T>` and `Queue<T>` keep their contents typed.
- How type argument inference worksHow TypeScript picks type arguments from a call's inference sites, why callbacks are inferred last, and how `NoInfer` stops an argument from widening `T`.
Type-level programming
- The keyof and typeof type operatorsDeriving types from what already exists: keyof for a type's keys, type-level typeof for a value's type, and keyof typeof to get keys from a runtime object.
- Indexed access typesLooking up a property's type with T[K]: nested lookups, unions of keys, T[keyof T], T[number] for arrays, and the typeof arr[number] pattern.
- Utility types for objectsPartial, Required, Readonly, Pick, Omit and Record: deriving update payloads, public views and lookup tables from one model instead of copying it.
- Utility types for unions and functionsExclude, Extract and NonNullable for filtering unions; ReturnType, Parameters and Awaited for reading function types; NoInfer for steering inference.
- Mapped typesBuilding an object type by looping over keys: T[K] for property types, adding and removing readonly and ?, modifier preservation, and key remapping with as.
- Conditional typesChoosing between two types with `T extends U ? X : Y`, so a type can branch on its input the way an expression branches on a value.
- The infer keywordDeclaring a type variable inside a conditional's `extends` clause so TypeScript fills it in, to pull element, return and promise types out of other types.
- Distributive conditional typesWhy a conditional type applied to a union runs once per member, how `[T] extends [U]` turns that off, and why `never` in gives `never` out.
- Template literal typesBuilding string types with backtick syntax, generating unions from combinations, and pulling strings apart with `infer`.
- Recursive typesTypes that refer to themselves: JSON values and trees, deep transformations like DeepReadonly, the instantiation depth limit, and tail recursion.
Classes and decorators
- Classes and access modifiersWhat TypeScript adds to JavaScript classes: field declarations, public/private/protected, private vs #private, parameter properties, and override.
- Abstract classes and implementing interfacesChecking a class against an interface with implements, sharing code through abstract classes, and how to choose between the two.
- DecoratorsTypeScript 5's standard decorators, the (value, context) signature, field and accessor decorators, and how legacy experimentalDecorators differs.
Modules and declaration files
- Modules and type-only importsHow TypeScript decides which imports survive compilation, and how import type, isolatedModules, and verbatimModuleSyntax make that explicit.
- Module resolutionHow TypeScript finds the file behind an import under nodenext and bundler, why extensions and exports matter, and what paths does and doesn't do.
- Namespaces: the legacy module systemWhy TypeScript has namespaces, what they compile to, why ES modules replaced them, and where they still appear in global declaration files.
- Declaration files and DefinitelyTypedWhat .d.ts files are, where a package's types come from, how @types packages are found through types and typeRoots, and what skipLibCheck skips.
- Writing declaration files and module augmentationTyping an untyped package with declare module, then extending a library's or the global scope's types with module augmentation and declare global.
TypeScript in practice
- Typing asynchronous codeHow TypeScript types promises and async functions: Promise<T>, Awaited<T>, Promise.all tuples, unknown in catch, and the floating promises tsc misses.
- Branded types and nominal typingWhy two string IDs are interchangeable in TypeScript, and how a brand makes UserId and OrderId distinct types with no runtime cost.
- Validating untrusted data at runtimeTypes vanish at runtime, so API responses and form input need a real check. Schema libraries like Zod and Valibot validate data and infer the type.
- Reading and debugging type errorsHow to read a long TypeScript error from the bottom up, inspect what the checker inferred, and corner a confusing error until it points at the real line.
- Testing your typesRuntime tests can't see a wrong type. Type tests can: @ts-expect-error for code that must fail, expectTypeOf in Vitest or expect-type, and tsd.
- Linting with typescript-eslintSet up typescript-eslint with flat config and typed linting, and catch the async and any-related bugs that tsc lets through.
- Migrating a JavaScript codebase to TypeScriptMove a JavaScript project to TypeScript gradually with allowJs, checkJs, JSDoc types, and strictness you tighten one file or one flag at a time.
- Project references and monoreposSplit a large TypeScript repo into composite projects linked with references, build them with tsc --build, and know when workspace packages suffice.
- Publishing a typed libraryShip declaration files with your package, wire them up through package.json exports with types first, and check the result with Are the Types Wrong.