TypeScript Tutorial
Learn TypeScript
JavaScript with syntax for types.
01
TypeScript Introduction
02
Basic Types
03
Arrays and Tuples
04
Objects and Interfaces
05
Type Aliases and Unions
06
Functions
07
Enums and Classes
08
Generics and Type Narrowing
09
Utility Types
10
Operators & Narrowing
11
Interfaces & Object Types
12
Advanced Types
TypeScript Reference
143 pages · 8 groups · syntax, parameters and worked examples
Utility Types22
Partial<Type>Constructs a type with every property of Type made optional, for patches and partial updates.Required<Type>Constructs a type where every property of Type is mandatory, removing all optional markers.Readonly<Type>Marks every property of Type as readonly so the type checker blocks reassignment.Record<Keys, Type>Builds an object type whose keys come from a union and whose values all share one type.Pick<Type, Keys>Constructs a type from Type keeping only the named properties.Omit<Type, Keys>Constructs a type from Type with the named properties removed.Exclude<UnionType, ExcludedMembers>Removes from a union every member assignable to the second type, producing a narrower union.Extract<Type, Union>Keeps only the members of a union that are assignable to a second type.NonNullable<Type>Removes null and undefined from a type, leaving only its definitely-present members.Parameters<Type>Extracts the argument types of a function type as a tuple, preserving names and optionality.ConstructorParameters<Type>Extracts a constructor's argument types as a tuple from a class's static side.ReturnType<Type>Extracts the return type of a function type, so a value type can be derived instead of duplicated.InstanceType<Type>Extracts the instance type a constructor produces, usually written as InstanceType<typeof SomeClass>.Awaited<Type>Unwraps a type the way await does, recursively resolving nested promises and thenables.NoInfer<Type>Blocks a type parameter from being inferred at that position so another argument decides it.ThisParameterType<Type>Extracts the type of a function's explicit this parameter, or unknown when it has none.OmitThisParameter<Type>Produces the function type left after binding, with the explicit this parameter removed.ThisType<Type>Marks an object literal's methods so this is contextually typed, without changing the type itself.Uppercase<StringType>Converts every character of a string literal type to uppercase inside the type system.Lowercase<StringType>Converts every character of a string literal type to lowercase inside the type system.Capitalize<StringType>Uppercases the first character of a string literal type, leaving the rest untouched.Uncapitalize<StringType>Lowercases the first character of a string literal type, leaving the rest untouched.
Type Operators15
keyofProduces the union of an object type's property names as string or numeric literal types.typeof (type query)Refers to the type of an existing variable or property from inside a type position.Indexed access types (T[K])Looks up the type of one or more properties on another type using bracket notation.Conditional types (T extends U ? X : Y)Selects between two types based on whether one type is assignable to another.inferDeclares a placeholder type variable inside a conditional type's extends clause to capture part of a type.Distributive conditional typesApplies a conditional type to each member of a union separately when the checked type is a naked type parameter.Mapped typesBuilds a new object type by transforming every property of an existing one.Mapped type modifiers (+/- readonly, ?)Adds or removes readonly and optional modifiers as a mapped type copies each property.Key remapping with asRenames or filters the keys a mapped type produces by computing a new key per property.Template literal typesBuilds string literal types by interpolation, expanding unions into every combination.satisfiesChecks an expression against a type without widening the expression's own inferred type.as constFreezes a literal expression so its type stays exact and its arrays become readonly tuples.as (type assertion)Tells the compiler to treat an expression as a different type, with no runtime conversion at all.Non-null assertion (!)Removes null and undefined from an expression's type without any runtime check.Recursive typesDescribe self-nesting data such as JSON or trees by referring to the type alias inside its own definition.
Generics7
Generic functionsDeclare type parameters on a function so its arguments and return type stay linked at every call site.Generic interfacesParameterise an interface so one declaration describes a family of shapes over any element type.Generic classesParameterise a class so each instance carries its own element type across fields, methods and returns.extends (generic constraint)Restrict a type parameter to types that match a shape, so its members are usable inside the body.Generic parameter defaultsGive a type parameter a fallback type so callers can omit it and still get a precise type.const type parametersInfer literal and readonly tuple types at the call site without making callers write as const.Variadic tuple typesSpread a generic tuple type inside another tuple to type concat, curry and partial application.
Narrowing & Type Guards10
is (type predicate)Declares that a boolean function narrows one of its parameters to a more specific type.asserts (assertion functions)Narrows a value for the rest of the scope by throwing when a runtime check fails.typeof narrowingNarrows a union by testing a value's runtime type tag with the typeof operator.instanceof narrowingNarrows a value to a class type by testing its prototype chain at runtime.in operator narrowingNarrows a union by testing whether a property name exists on the object.Discriminated unionsModels a set of mutually exclusive shapes with a shared literal tag the compiler can switch on.Exhaustiveness checking with neverTurns a missed union member into a compile error by assigning the leftover value to never.Truthiness narrowingNarrows a value by testing it for truthiness, removing null, undefined and the other falsy types.Equality narrowingNarrows types by comparing values with ===, !==, == and !=, including the null-and-undefined shortcut.this is T (this-based guards)Narrows the receiver itself by declaring a method whose return type is this is Type.
Special Types20
anyDisables type checking for a value, allowing any operation and any assignment.unknownAccepts any value but permits no operation on it until you narrow it to a real type.neverMarks values that never occur — thrown functions, empty unions, and exhaustive switch checks.voidMarks a function as returning no useful value, while still accepting callbacks that return one.nullNames the intentional-absence value as its own type once strictNullChecks is enabled.undefinedTypes an uninitialised or missing value, distinct from a property marked optional with ?.objectMatches any non-primitive value — objects, arrays and functions, but never a string or number.symbolTypes unique property keys created by Symbol(), with unique symbol for a single fixed identity.bigintTypes arbitrary-precision integers, which require target ES2020 and never mix with number.stringTypes text primitives — the lowercase form, not the String wrapper object.numberTypes every JavaScript number — integers and floats alike, all IEEE 754 doubles.booleanTypes the two values true and false — literally the union true | false.Literal typesPin a value's type to one exact string, number or boolean instead of the widened primitive.Union types (|)Accept a value that may be any one of several types, then narrow before using branch-specific members.Intersection types (&)Combine several object types into one value that must satisfy every member simultaneously.Tuple typesType a fixed-length array position by position, with optional, rest and labelled elements.Array typesType a list of values with T[] or Array<T>, and lock it against mutation with readonly T[].Function typesDescribe callable and constructable values with call signatures, construct signatures and parameters.Index signaturesType objects with unknown keys but known value types, such as dictionaries and lookup tables.this typeReturn the current class type from a method so fluent chains keep working in subclasses.
Declarations & Keywords22
interfaceDeclares a named object shape that can extend other types and be reopened to add members.typeNames any type at all, including unions, tuples, mapped and conditional types.enumDeclares a named set of constants that emits a real runtime object of keys and values.const enumDeclares an enum whose members are inlined at each use site, emitting no runtime object.namespaceGroups related declarations under one name, emitting an IIFE when it contains values.declareDescribes the type of something that already exists at runtime without emitting any code.declare globalAdds or patches declarations in the global scope from inside a module.Declaration mergingCombines two same-named declarations into one definition across interfaces, namespaces, enums and more.abstractMarks a class that cannot be instantiated, or a member that subclasses must implement.implementsChecks that a class satisfies an interface without changing the class type or inferring parameters.readonlyBlocks reassignment of a property, index signature, array or tuple at compile time only.public / private / protectedControls class member visibility during type checking only; nothing is hidden at runtime.#private fieldsDeclares a hard-private class member that JavaScript itself enforces at runtime, not just at compile time.overrideMarks a member as deliberately replacing a base-class member, so renaming the base becomes a compile error.accessorDeclares an auto-accessor: a get/set pair over a hidden private backing field, mainly for decorators.staticAttaches a property, method or initializer block to the class itself rather than to its instances.Parameter propertiesDeclares and assigns a class field directly from a constructor parameter marked public, private or readonly.get / set accessorsDefines a property backed by code, with a setter that may accept wider types than the getter returns.Function overloadsDeclares several call signatures for one function so callers see only the shapes you intend.this parameterTypes the this value of a function through a fake first parameter that is erased on emit.DecoratorsWraps a class, method, field or accessor with a function that runs when the class is defined.abstract new (constructor types)Types a constructor that may be abstract, so mixins and factories can accept an abstract class.
Modules & Ambient Declarations8
import typeImports a binding for type positions only, guaranteeing it is erased from the emitted JavaScript.export typeRe-exports or exports a binding for type use only, so the declaration never appears in emitted JavaScript.import =Binds a CommonJS require or an existing namespace to a local name that works in both type and value positions.export =Declares that a module's entire export is one value, matching CommonJS module.exports = x.Ambient modulesDeclares the shape of a module that has no TypeScript source, including wildcard patterns like "*.css".Module augmentationAdds members to an existing module's types from your own code, without forking the package's declarations.Triple-slash directivesDeclares compile-time dependencies on files, type packages or lib files from a comment at the top of a file.import defer / import attributesPasses host-specific attributes on an import and defers a module's evaluation until first property access.
Compiler Options (tsconfig)39
strictTurns on every strict type-checking flag at once, including ones added in future releases.strictNullChecksGives null and undefined their own types instead of letting them inhabit every other type.noImplicitAnyErrors whenever TypeScript would silently fall back to any for an untyped parameter or member.strictFunctionTypesChecks function parameters contravariantly so a narrower handler cannot stand in for a wider one.strictPropertyInitializationErrors when a class field is declared but never assigned a value in the constructor.strictBindCallApplyType-checks the arguments and result of call, apply and bind instead of returning any.noImplicitThisErrors when this is used in a context where its type cannot be determined.useDefineForClassFieldsEmits class fields with Object.defineProperty semantics instead of plain assignment.alwaysStrictParses every file in ECMAScript strict mode and emits "use strict" at the top of the output.exactOptionalPropertyTypesStops an optional property from accepting an explicit undefined unless its type says so.noUncheckedIndexedAccessAdds undefined to every read through an index signature or numeric array index.targetSets which ECMAScript version TypeScript emits and which default library declarations come with it.moduleSets the module format tsc emits: esnext, commonjs, node16/nodenext or preserve.moduleResolutionChooses the algorithm that turns an import specifier into a file on disk.libSelects which built-in type declarations are loaded, independently of target.jsxControls how JSX is emitted: preserved, React.createElement, or the automatic runtime.esModuleInteropEmits interop helpers so default and namespace imports of CommonJS modules work.allowSyntheticDefaultImportsAllows default imports from modules with no default export, without changing emit.verbatimModuleSyntaxEmits every import and export exactly as written unless it carries a type modifier.isolatedModulesFlags code that a single-file transpiler such as Babel or esbuild cannot compile correctly.skipLibCheckSkips type checking of all .d.ts files, trading accuracy for build speed.pathsMaps import specifiers such as @/* to folders for type checking only.baseUrlSets the directory that bare import specifiers resolve against.outDirSets the directory emitted JavaScript is written to, mirroring the source tree.rootDirSets the input root that determines the folder structure TypeScript mirrors into outDir.declarationEmits .d.ts files describing your public API so consumers of the package get types.sourceMapGenerates .js.map files so debuggers and stack traces point back at the original source.noEmitRuns the compiler as a type checker only, writing no JavaScript, maps or declarations.allowJsAllows .js files into the program so TypeScript can compile and import them.checkJsReports type errors in JavaScript files, using JSDoc comments as the type annotations.resolveJsonModuleAllows importing .json files, typing the import from the file's actual contents.incrementalCaches compilation state in .tsbuildinfo so later runs only re-check what changed.compositeMarks a project as referenceable, the prerequisite for project references and tsc --build.references (project references)Lists the projects this one depends on so tsc --build can order and cache the builds.noUnusedLocalsReports an error on declared local variables that are never read.noImplicitReturnsErrors when some code path through a function falls off the end without returning.moduleDetectionControls whether TypeScript treats each source file as a module or as a global script.extendsInherits compiler options from another tsconfig file, then overrides them locally.include / exclude / filesSelects which source files enter the program, using globs, an allowlist, or a skip list.