TypeScript Documentation
Concise, example-driven TypeScript reference. Read the concept, see the code, then practice it in a Coddy journey.
Start a guided TypeScript journeyGetting Started
- What Is TypeScriptTypeScript is JavaScript with static types. You annotate values with types, the compiler checks them before the code runs, and the output is plain JavaScript that runs in any browser or in Node.js, Deno and Bun.
- TypeScript vs JavaScriptTypeScript is JavaScript plus a static type system that is checked before the code runs. Compare the two side by side: syntax, what the type checker catches, the build step, runtime speed, learning curve, and how to migrate a JavaScript project.
- Install TypeScriptInstall TypeScript with npm as a project dev dependency, check the version with npx tsc --version, create a tsconfig.json with tsc --init, and compile your first file. Covers global installs, pnpm, Yarn and Bun, and the errors people hit.
- Run TypeScriptFive ways to run a .ts file: compile with tsc and run the JavaScript, run it directly with node file.ts (type stripping), use tsx or ts-node, or use Deno and Bun. Which ones check types, which syntax each supports, and which to pick.
- tsconfig.jsontsconfig.json marks a folder as a TypeScript project and sets the compiler options. The options that matter (target, module, moduleResolution, strict, rootDir, outDir, include, lib, types, noEmit, skipLibCheck), a recommended starting config, extends, and what TypeScript 7 changed.
- TypeScript 7TypeScript 7 is the TypeScript compiler rewritten in Go as a native program: about ten times faster, with the same tsc command and the same language. What changed for users (new defaults, removed options, the missing JavaScript API), which tools still need TypeScript 6, and how to upgrade.
- CommentsTypeScript uses JavaScript's // and /* */ comments, plus JSDoc /** */ comments that editors show on hover. It also reads a few special comments: @ts-expect-error, @ts-ignore, @ts-nocheck, @ts-check and /// <reference> directives.
- TypeScript vs PythonTypeScript and Python are both high-level, garbage-collected languages, but TypeScript checks its types before the code runs and Python's type hints are optional and ignored at runtime. A side-by-side comparison of typing, runtime, speed, ecosystems and use cases, with the same program in both.
Basic Types
- Basic TypesThe built-in TypeScript types: string, number, boolean, bigint, symbol, null and undefined, plus arrays and objects at a glance. How to write a type annotation, why there is no integer type, and why you write string instead of String.
- Type InferenceTypeScript works out most types from the values you write. Learn what it infers for variables, let vs const, objects, arrays and return values, how callbacks get their types from context, and where you still need an annotation.
- StringsWorking with strings in TypeScript: template literal interpolation, multiline strings, checking if a string contains a substring, the common methods and the types they return, and string literal types.
- String to NumberConvert a string to a number in TypeScript with Number(), parseInt(), parseFloat() or unary +, see how each handles inputs like "42px", "" and "1e3", check for NaN safely, and convert numbers back to strings.
- ArraysHow to type arrays in TypeScript: T[] vs Array<T>, arrays of objects, arrays that hold several types, readonly arrays, and what map, filter, reduce and find return. Plus the includes pitfall with literal arrays.
- TuplesA TypeScript tuple is an array with a fixed number of elements whose types are known by position, like [string, number]. Learn the syntax, named, optional and rest elements, readonly tuples and as const, returning tuples from functions, and how tuples differ from arrays.
- Object TypesHow to type objects in TypeScript: inline object types, optional properties with ?, readonly properties, nested objects, methods, excess property checks, and the difference between object, {} and Object.
- EnumsA TypeScript enum is a named set of constants, like enum Direction { Up, Down }. Learn numeric and string enums, the JavaScript an enum compiles to, reverse mapping, iterating over an enum, const enums, and when a union of string literals or an as const object is the better choice.
Special Types
- Literal TypesA literal type is a type with exactly one value, like "GET" or 404. Learn string, number and boolean literal types, unions of literals, why let widens and const does not, what as const does, and const type parameters.
- any vs unknownBoth any and unknown accept every value. any switches type checking off for that value, while unknown makes you check the value before you use it. Learn the differences, how to narrow unknown, noImplicitAny, and where any sneaks into typed code.
- never Typenever is the type with no values. It is the return type of functions that never finish, the type left over when narrowing has ruled out every case, and the tool behind exhaustive switch checks. Learn where it comes from and how it differs from void.
- null and undefinedWith strictNullChecks, null and undefined are separate types that TypeScript makes you handle. Learn how to check for them, optional chaining (?.), the double question mark (??) and ??=, and the difference between an optional property and | undefined.
- Non-Null Assertion (!)An exclamation mark after a value, like user!, is the non-null assertion operator: it removes null and undefined from the type without any runtime check. Learn what x! does, the definite assignment forms let x!: T and prop!: T, why they are risky, and safer alternatives.
Interfaces and Type Aliases
- InterfacesAn interface names the shape of an object: which properties it has and what types they hold. Learn how to declare one, optional and readonly properties, methods, index signatures, extending, implementing in a class, declaration merging, generic interfaces and how to give an interface default values.
- Type AliasesA type alias gives a name to any type with the type keyword: object shapes, unions, tuples, functions, generics and recursive types. Learn the syntax, what each form looks like, and why an alias is only a name and not a new, separate type.
- Interface vs Typeinterface and type can both describe object shapes, and most of the time either works. Learn the real differences: declaration merging, unions and mapped types, extends vs intersections, implicit index signatures, error reporting and compiler performance, plus a clear rule for choosing.
- extends KeywordThe extends keyword builds one type from another. Learn how to extend an interface (once or from several), extend a type alias with &, override a property type, replace properties with Omit, and what extends means in classes, generic constraints and conditional types.
- Union TypesA union type like string | number means a value can be any one of several types. Learn what you can do with a union (only what every member supports), how to narrow it, unions of literals and object types, and the difference between (A | B)[] and A[] | B[].
- Intersection TypesAn intersection type A & B describes a value that is both A and B at once, so it has every member of both. Learn how to combine object types with &, why conflicting properties become never, how intersections of unions keep only the shared members, and when to use extends instead.
- Discriminated UnionsA discriminated union is a union of object types that share a literal tag property, like kind or status. Checking the tag narrows the whole object. Learn the pattern, switch narrowing, exhaustive checks with never, and how to model API results, request state and state machines.
Functions
- FunctionsHow to type functions in TypeScript: annotate every parameter, annotate or infer the return type, use void for functions that return nothing, and type arrow functions, function expressions, async functions and the this parameter.
- Function TypesHow to write the type of a function in TypeScript: the arrow syntax (a: number) => string, type aliases for functions, typing arrow functions and callbacks, call and construct signatures, and why the Function type is too loose.
- Optional ParametersMark a TypeScript parameter optional with ?, give it a default value, or collect any number of arguments with a rest parameter. Covers the order rules, omitted vs undefined, options objects and optional parameters in function types.
- Function OverloadingTypeScript function overloads let one function have several call signatures, each with its own return type. Learn the overload signatures plus implementation pattern, the rules the compiler checks, when a union parameter is better, and overloads in classes.
Narrowing and Type Checks
- Type NarrowingNarrowing is how TypeScript turns a wide type like string | number into a specific one inside an if, a switch or after an early return. Every narrowing form in one place: typeof, truthiness, equality, in, instanceof, assignments, type predicates and discriminated unions.
- typeof Operatortypeof has two jobs in TypeScript. In code it is the JavaScript operator that returns "string", "number", "object" and so on at run time, and TypeScript narrows on it. In a type it is the type query that copies the type of a variable, as in keyof typeof obj and ReturnType<typeof fn>.
- instanceof Operatorinstanceof checks at run time whether an object was created by a class, and TypeScript narrows the variable to that class. How it works with your own classes and Error subclasses, why it cannot check interfaces or type aliases, and where it gives surprising answers.
- Type GuardsA type guard is a runtime check that TypeScript understands. Learn the built-in guards, how to write your own with a value is Type predicate, how to check if an object is of a type, assertion functions with asserts, and how to validate unknown data.
- Type AssertionsThe as keyword tells TypeScript to treat a value as a different type. It is not a cast: nothing is converted or checked at run time. Learn the as and angle-bracket syntax, what the compiler allows, double assertions through unknown, and when a type guard is the better tool.
- satisfies OperatorThe satisfies operator checks that a value matches a type without changing the value's inferred type. Learn what it does, how it compares with a type annotation and with as (the same object written three ways), how it combines with as const, and why it fits config objects.
Classes
- ClassesTypeScript classes are JavaScript classes with typed fields, methods and constructors. Learn how field declarations and strictPropertyInitialization work, how to type this, getters and setters, static members, implements, and how a class doubles as a type.
- ConstructorsHow to type a class constructor in TypeScript: typed and optional parameters, parameter properties like constructor(private name: string), field initialization order, constructor overloads, super calls in subclasses, private constructors and constructor types with new.
- Access ModifiersTypeScript has three access modifiers, public, private and protected, plus readonly. Learn what each allows, why TypeScript private is a compile-time check while JavaScript #private fields are enforced at runtime, and which to choose.
- InheritanceClass inheritance in TypeScript: extends and super, overriding methods with compatible types, the override keyword and noImplicitOverride, protected members, redeclaring fields with declare, and when implements is the better tool.
- Abstract ClassesAn abstract class in TypeScript is a base class that cannot be instantiated and can leave methods for subclasses to implement. Learn abstract methods and properties, the template method pattern, abstract constructor types, and when an interface is the better choice.
- DecoratorsDecorators are functions that wrap or replace class members with the @ syntax. Learn the standard decorators TypeScript supports without any flag (class, method, getter, field and accessor), decorator factories, addInitializer, and how they differ from the legacy experimentalDecorators used by Angular and NestJS.
Generics
- GenericsGenerics let a function, interface, type or class work with many types while keeping them connected: what goes in decides what comes out. Learn generic functions, type argument inference, several type parameters, generic interfaces and classes, defaults, and when not to use generics.
- Generic ConstraintsA generic constraint, T extends Something, limits which types a type parameter accepts and lets the function use what the constraint guarantees. Covers extends with object shapes and interfaces, K extends keyof T for safe property access, constraints on primitives, and the errors you will meet.
Type Operators
- keyof Operatorkeyof takes an object type and gives you the union of its property names. Learn keyof with interfaces, keyof typeof for plain objects, typed property access with generics, index signatures (string | number), and why Object.keys returns string[].
- Indexed Access TypesAn indexed access type reads the type of a property out of another type: Person["age"] is number. Learn T["key"], union keys, T[keyof T], T[number] for array elements, tuple indexes, and (typeof arr)[number] to turn a const array into a union.
- Mapped TypesA mapped type builds a new object type by looping over keys: { [K in keyof T]: ... }. Learn the syntax, the readonly and ? modifiers with + and -, key remapping with as, filtering keys, and how Partial, Readonly, Required, Pick and Record are written.
- Conditional TypesA conditional type picks one of two types based on a test: T extends U ? X : Y. Learn the syntax, how conditional types distribute over unions (and how to stop it), extracting types with infer, and how to write ReturnType yourself.
- Template Literal TypesTemplate literal types build string literal types with the same backtick syntax as JavaScript template strings: `on${Capitalize<E>}`. Learn the syntax, how unions multiply, Uppercase and Capitalize, patterns like `${number}px`, mapped type getters, and parsing strings with infer.
- Branded TypesA branded type is a primitive with an invisible tag, like string & { readonly __brand: "UserId" }, so a UserId cannot be passed where an OrderId is expected. Learn how brands work, constructor functions that validate, a generic Brand helper, unique symbol brands and branded numbers.
Utility Types
- Utility TypesEvery built-in TypeScript utility type in one place: Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, NonNullable, Parameters, ReturnType, Awaited, the string types and more, each with a one-line description and a runnable example.
- RecordRecord<K, V> is the object type whose keys are K and whose values are all V. Learn Record with string keys and with union keys (every key required), Partial<Record>, looping over a Record with typed keys, the missing-key pitfall, and when to use an index signature or a Map instead.
- Partial and RequiredPartial<T> makes every property of T optional, which is exactly the type of an update or patch object. Learn Partial in update functions, why it is shallow, how to write a DeepPartial, the explicit undefined pitfall, and its opposite Required<T>.
- OmitOmit<T, K> creates a type with every property of T except the keys K. Learn Omit with one and several keys, overriding a property type, removing the property at runtime, Omit vs Exclude and Pick, why Omit accepts keys that do not exist, a strict Omit, and Omit on union types.
- PickPick<T, K> creates a type with only the properties of T whose keys are in K. Learn Pick with one or several keys, how it checks keys, Pick vs Omit, picking from nested types, a typed pick() function, and picking properties by their value type.
- readonly and ReadonlyThe readonly modifier and the Readonly<T> utility type stop code from reassigning properties. Learn readonly properties and class fields, Readonly<T>, readonly arrays (readonly T[] and ReadonlyArray), ReadonlyMap and ReadonlySet, why readonly is shallow and compile-time only, and how it compares with Object.freeze and as const.
- Exclude and ExtractExclude, Extract and NonNullable filter the members of a union type. Learn what each keeps and removes, how to pick union members by shape, how they are built from conditional types, and how they differ from Omit and Pick.
- ReturnType and ParametersReturnType, Parameters, ConstructorParameters, InstanceType and Awaited extract types from functions, classes and promises. Learn how to use them with typeof, how to get the result type of an async function, what happens with overloads and generics, and how ReturnType is built with infer.
Loops and Collections
- LoopsEvery way to loop in TypeScript and the types each one gives you: the classic for loop, for...of over arrays, maps and strings, for...in and its string keys, forEach (no break, no await), typed loops over object keys, and while.
- Switch StatementThe switch statement in TypeScript: syntax, how each case narrows a union type, exhaustive switches that fail to compile when a case is missing, the switch (true) pattern, fallthrough and block scoping.
- MapHow to use Map in TypeScript: create a typed Map<K, V>, why get returns V | undefined, set, has and delete, iterating in insertion order, object keys, converting to and from objects and JSON, Map vs object vs Record, and typing array.map().
- DictionaryTypeScript has no dictionary or hashmap class; you type a key-value lookup with an index signature, Record<K, V> or Map<K, V>. Learn each one, how to check if a key exists, add, delete and iterate, and why noUncheckedIndexedAccess matters for dictionaries.
Async and Errors
- PromisesHow promises are typed in TypeScript: the Promise<T> type, typing new Promise and resolve, how then changes the type, why catch gives you any, Promise.all with tuple results, Promise.allSettled result types, and wrapping callback APIs in a typed promise.
- Async/AwaitHow async and await are typed in TypeScript: an async function returns Promise<T>, await unwraps it, errors are caught with try/catch, top-level await needs an ES module, and the difference between awaiting one by one, awaiting in parallel, and the forEach pitfall.
- Error HandlingError handling in TypeScript: why the catch variable is unknown, how to narrow it with instanceof Error, throwing errors, writing custom error classes with name and cause, and the Result type pattern for errors you expect.
- SleepTypeScript has no built-in sleep, but one line gives you one: a function that returns a Promise<void> resolved by setTimeout. Learn how to await it, pause inside loops, retry with a delay, cancel a sleep, and why there is no blocking sleep in JavaScript.
Modules and Tooling
- ModulesEvery TypeScript file with a top-level import or export is a module. Learn named and default exports, import type and export type, how the module setting decides between ES module and CommonJS output, and why node16 and nodenext want .js extensions in imports.
- NamespacesA TypeScript namespace groups values and types under one name and compiles to a plain object. Learn the syntax, how namespaces merge with each other and with functions and classes, why ES modules replaced them, and where you still meet them: declaration files and global augmentation.
- Declaration FilesA .d.ts file describes the types of JavaScript code without containing any of it, and the declare keyword does the same inside a .ts file. Learn how declaration files are generated, where @types packages fit, how to type an untyped module, and how declare global and module augmentation extend existing types.
- Strict Modestrict: true in tsconfig.json turns on a family of type checks: noImplicitAny, strictNullChecks, strictPropertyInitialization and five more. See what each one catches, how to enable strict mode in an existing project, and the useful flags strict does not include.
- JSONJSON.parse returns any, so TypeScript trusts whatever type you give the result. Learn how to type parsed JSON, validate it with a type guard, turn a JSON sample into an interface, import .json files, and what JSON.stringify does to Dates, Sets and undefined.
Going Further
- Best PracticesEight TypeScript habits that prevent real bugs: keep strict on, use unknown instead of any, let inference work, prefer unions to enums, check config with satisfies, model state with discriminated unions, avoid ! and as, and make data readonly. Each comes with a runnable before and after.
- Interview Questions25 TypeScript interview questions with short, correct answers and code, grouped from beginner to advanced: any vs unknown, interface vs type, generics, narrowing, utility types, mapped and conditional types, structural typing, tsconfig and TypeScript 7.