TypeScript Reference
Every TypeScript keyword, type operator, utility type, compiler option and error code in one place: concise, accurate pages with live examples that type-check and run on TypeScript 7 and Node 24.
Keywords and Declarations
-
let and constBlock-scoped variables with inferred types. -
varFunction-scoped variables and why to avoid them. -
typeType aliases for any type expression. -
interfaceObject shapes, extension and declaration merging. -
functionTyped function declarations and expressions. -
Arrow functionsTyped arrow functions and contextual typing. -
returnReturn types and inferred returns. -
if and elseConditionals that narrow types. -
switchSwitch statements and exhaustive checks. -
for, for...of, for...inLoops and the types of their variables. -
while and do...whileCondition-controlled loops. -
break and continueLeaving and skipping loop iterations. -
try, catch, finallyError handling and the type of caught values. -
throwThrowing values and the never type. -
async and awaitTyped asynchronous functions. -
yield and function*Typed generators. -
classClass declarations with typed members. -
extendsClass inheritance and generic constraints. -
implementsChecking that a class matches an interface. -
newConstructing instances and construct signatures. -
thisThe this type and this parameters. -
superCalling parent constructors and methods. -
staticStatic members and static blocks. -
abstractAbstract classes and members. -
public, private, protectedMember visibility modifiers. -
#privateJavaScript private fields. -
readonlyRead-only properties, arrays and tuples. -
overrideMarking members that override a base class. -
accessorAuto-accessor class fields. -
enumNumeric and string enums. -
const enumEnums inlined at compile time. -
namespace and moduleLegacy internal modules and merging. -
declareAmbient declarations without emitting code. -
import and exportES module syntax with types. -
import typeType-only imports that are erased. -
export typeType-only exports and re-exports. -
export = and import =CommonJS-style module syntax. -
using and await usingExplicit resource management. -
typeof (value)The JavaScript typeof operator and narrowing. -
instanceofNarrowing to class instances. -
inProperty checks that narrow unions. -
voidThe void operator and the void type. -
deleteDeleting properties and optional-operand rules. -
Labeled statementsLabels with break and continue. -
debuggerPausing in a debugger. -
"use strict"Strict mode directives and TypeScript.
Primitive and Special Types
-
stringText values and string methods. -
numberFloating-point numbers, NaN and Infinity. -
bigintArbitrary-size integers and literals. -
booleanTrue and false, truthiness and narrowing. -
symbolSymbols and unique symbol. -
nullThe null value and strictNullChecks. -
undefinedMissing values and optional types. -
anyThe escape hatch that turns off checking. -
unknownThe safe top type that needs narrowing. -
neverThe type of values that never occur. -
void (type)Return type of functions that return nothing. -
objectAny non-primitive value. -
Object and {}The wrapper type and the empty type. -
FunctionThe broad Function type and why to avoid it. -
String, Number, BooleanWrapper object types you should not use. -
Array<T> and T[]Typed arrays, readonly arrays and methods. -
TuplesFixed-length typed arrays, labels and rest elements. -
readonly T[]Read-only arrays and ReadonlyArray. -
Enum typesEnum members as types and values. -
unique symbolSymbols with their own identity type. -
Template literal typesString types built from other types. -
Uppercase, Lowercase, CapitalizeBuilt-in string manipulation types. -
Promise<T>Typing asynchronous results. -
Iterable and IteratorTypes for iteration protocols. -
Date and RegExpBuilt-in object types for dates and patterns. -
Map and SetTyped collections with keys and values. -
WeakMap and WeakSetWeak collections with object keys. -
Typed arraysUint8Array, Float64Array and friends. -
ErrorError types and custom error classes.
Literal and Object Types
-
String literal typesTypes that allow one exact string. -
Number literal typesTypes that allow one exact number. -
Boolean literal typesThe true and false types. -
Object typesInline object shapes and property modifiers. -
Optional propertiesThe ? modifier and undefined. -
Readonly propertiesProperties that cannot be reassigned. -
Index signaturesObjects with arbitrary string or number keys. -
Call signaturesDescribing callable objects. -
Construct signaturesDescribing constructors. -
Method signaturesMethod syntax versus property syntax. -
Union typesA | B: a value of one of several types. -
Intersection typesA & B: values that satisfy both types. -
Discriminated unionsTagged unions narrowed by a literal field. -
Function typesParameter lists, return types and overloads. -
Optional and default parametersThe ? modifier and default values. -
Rest parametersVariadic parameters and tuple rest types. -
Function overloadsSeveral call signatures for one function. -
this parametersDeclaring the type of this in a function. -
Labeled and variadic tuplesNamed elements and spread in tuples. -
Recursive typesTypes that refer to themselves. -
Excess property checksWhy object literals are checked strictly. -
Weak typesTypes where every property is optional.
Type Operators
-
keyofThe union of an object type's keys. -
typeof (type)Getting the type of a value. -
Indexed access typesT[K]: the type of a property. -
Conditional typesT extends U ? X : Y. -
inferCapturing types inside conditional types. -
infer ... extendsConstraining inferred types. -
Mapped typesTransforming every property of a type. -
Mapping modifiersAdding and removing readonly and optional. -
Key remapping with asRenaming keys in mapped types. -
Distributive conditional typesHow unions are spread across a conditional. -
satisfiesChecking a value against a type without widening. -
as (type assertion)Telling the compiler a more specific type. -
as constLiteral, readonly inference for values. -
Non-null assertion (!)Removing null and undefined from a type. -
Definite assignment (!:)Declaring a property is assigned later. -
Optional chaining (?.)Safe access to nullable values. -
Nullish coalescing (??)Defaults for null and undefined only. -
Logical assignment (??=, ||=, &&=)Assigning conditionally. -
Spread (...)Spreading arrays and objects with types. -
DestructuringTyped destructuring of arrays and objects. -
Type predicates (x is T)Custom type guards. -
Assertion functions (asserts)Functions that narrow by throwing. -
const type parametersInferring literal types in generics. -
in and out varianceVariance annotations on type parameters. -
Computed property keysSymbols and literals as property keys. -
Bitwise operatorsOperators on numbers and bigints. -
Equality and comparison=== versus == and type effects. -
Arithmetic operatorsMath operators and what they accept.
Utility Types
-
Partial<T>Makes every property optional. -
Required<T>Makes every property required. -
Readonly<T>Makes every property read-only. -
Record<K, T>An object type with given keys and value type. -
Pick<T, K>Keeps only the chosen properties. -
Omit<T, K>Removes the chosen properties. -
Exclude<T, U>Removes union members assignable to U. -
Extract<T, U>Keeps union members assignable to U. -
NonNullable<T>Removes null and undefined. -
ReturnType<T>The return type of a function type. -
Parameters<T>A function's parameters as a tuple. -
ConstructorParameters<T>A constructor's parameters as a tuple. -
InstanceType<T>The instance type of a constructor. -
ThisParameterType<T>The this parameter of a function type. -
OmitThisParameter<T>A function type without its this parameter. -
ThisType<T>Marker for the type of this in object literals. -
Awaited<T>The type a promise resolves to. -
NoInfer<T>Blocks inference from a position. -
Uppercase<S>Converts a string type to upper case. -
Lowercase<S>Converts a string type to lower case. -
Capitalize<S>Upper-cases the first character of a string type. -
Uncapitalize<S>Lower-cases the first character of a string type. -
ReadonlyArray<T>Arrays without mutating methods. -
ReadonlyMap and ReadonlySetRead-only views of Map and Set. -
PropertyKeyThe union of valid property key types. -
PromiseLike<T>The minimal thenable type. -
AsyncIterable and AsyncGeneratorTypes for async iteration. -
Disposable and AsyncDisposableTypes for using declarations. -
Custom helper typesCommon type-level helpers such as DeepPartial. -
Flatten and Unwrap helpersBuilding utility types by hand.
Generics
-
Generic functionsType parameters on functions. -
Generic interfacesInterfaces with type parameters. -
Generic classesClasses with type parameters. -
Generic type aliasesType aliases with type parameters. -
Generic constraintsLimiting type parameters with extends. -
Default type parametersFallback types for type parameters. -
Type argument inferenceHow the compiler picks type arguments. -
Constraints with keyofTyped property access functions. -
Multiple type parametersRelating several types in one signature. -
Constructor and factory typesGeneric factories with new signatures. -
Higher-order generic functionsGeneric functions that return generic functions. -
Variance and assignabilityCovariance, contravariance and invariance. -
const type parametersKeeping literal types when inferring. -
Recursive genericsGeneric types that reference themselves.
Narrowing and Type Guards
-
typeof guardsNarrowing primitives with typeof. -
Truthiness narrowingNarrowing with if (x) and ||. -
Equality narrowingNarrowing with === and !==. -
The in operatorNarrowing by property presence. -
instanceof guardsNarrowing to class instances. -
Discriminant narrowingNarrowing unions by a tag field. -
User-defined type guardsFunctions returning x is T. -
Assertion functionsFunctions returning asserts x is T. -
Exhaustiveness checkingUsing never to catch missing cases. -
Control flow analysisHow types change as code runs. -
Array.isArrayNarrowing to arrays. -
Inferred type predicatesGuards the compiler writes for you. -
switch (true)Narrowing with boolean case expressions. -
Aliased conditionsNarrowing through stored conditions.
Classes, Enums and Decorators
-
Class fieldsDeclaring and initializing properties. -
ConstructorsConstructor signatures and overloads. -
Parameter propertiesDeclaring fields in the constructor. -
MethodsTyped methods and this. -
Getters and settersAccessors and their types. -
Static membersStatic fields, methods and blocks. -
InheritanceExtending classes and overriding members. -
Abstract classesClasses that cannot be instantiated. -
Implementing interfacesClasses that satisfy interfaces. -
MixinsComposing behavior with class expressions. -
Private fieldsprivate versus #private. -
this typesFluent APIs with polymorphic this. -
Structural typing of classesWhy classes compare by shape. -
Numeric enumsAuto-incrementing enum values and reverse mapping. -
String enumsEnums with string values. -
Heterogeneous enumsMixing numbers and strings in an enum. -
const enumsInlined enums and preserveConstEnums. -
Computed and constant membersRules for enum member values. -
Enum alternativesUnion types and as const objects. -
Class decoratorsStandard decorators that wrap classes. -
Method decoratorsWrapping and replacing methods. -
Field decoratorsInitializing and transforming fields. -
Accessor decoratorsDecorating getters, setters and accessors. -
Decorator factoriesDecorators that take arguments. -
Decorator context objectWhat the context argument provides. -
experimentalDecoratorsThe legacy decorator mode.
Modules and Declaration Files
-
ES modulesImport and export in TypeScript. -
CommonJS modulesrequire, module.exports and TypeScript. -
Default and named exportsChoosing and typing exports. -
Re-exportsexport * and export { x } from. -
Type-only importsimport type and inline type modifiers. -
Dynamic import()Lazy loading with typed results. -
import.metaModule metadata and its type. -
Module resolutionHow TypeScript finds imported files. -
package.json exportsTyping packages with conditional exports. -
Path mappingpaths and baseUrl for aliases. -
ESM and CJS interopesModuleInterop and default imports. -
Importing JSONresolveJsonModule and import attributes. -
NamespacesLegacy namespaces and when they still matter. -
Triple-slash directives/// <reference> comments. -
Declaration files (.d.ts)Describing JavaScript with types. -
declare and ambient modulesdeclare module and declare global. -
Global augmentationExtending Window and built-ins. -
Module augmentationAdding to a library's types. -
@types packagesDefinitelyTyped and the types field. -
Generating declarationsdeclaration and declarationMap output. -
JSDoc type annotationsTypes in .js files with checkJs. -
The lib option and built-in typesWhich built-in typings are available. -
Writing a .d.ts fileA worked guide to typing a JavaScript library.
tsconfig: Type Checking Options
-
strictTurns on the whole strict family. -
noImplicitAnyErrors on inferred any. -
strictNullChecksSeparates null and undefined from other types. -
strictFunctionTypesContravariant function parameters. -
strictBindCallApplyChecks bind, call and apply. -
strictPropertyInitializationRequires class fields to be initialized. -
noImplicitThisErrors on an untyped this. -
alwaysStrictEmits "use strict" in every file. -
useUnknownInCatchVariablesMakes caught errors unknown. -
strictBuiltinIteratorReturnStricter return types for built-in iterators. -
exactOptionalPropertyTypesDistinguishes missing from undefined. -
noUncheckedIndexedAccessAdds undefined to indexed reads. -
noPropertyAccessFromIndexSignatureForces bracket access for index signatures. -
noImplicitReturnsErrors when some paths return nothing. -
noFallthroughCasesInSwitchErrors on fallthrough in switch. -
noImplicitOverrideRequires the override keyword. -
noUnusedLocalsErrors on unused local variables. -
noUnusedParametersErrors on unused parameters. -
allowUnreachableCodeControls unreachable code reporting. -
allowUnusedLabelsControls unused label reporting. -
skipLibCheckSkips checking declaration files. -
forceConsistentCasingInFileNamesErrors on inconsistent file name casing. -
noUncheckedSideEffectImportsChecks side-effect imports resolve. -
stripInternalRemoves @internal declarations.
tsconfig: Language, Modules and Emit Options
-
targetThe JavaScript version to emit. -
libWhich built-in typings to include. -
moduleThe module system of emitted code. -
moduleResolutionThe algorithm for finding modules. -
moduleDetectionHow files are classified as modules. -
esModuleInteropDefault-import interop for CommonJS. -
allowSyntheticDefaultImportsAllows default imports without a default export. -
isolatedModulesRequires files to compile on their own. -
verbatimModuleSyntaxKeeps imports and exports as written. -
erasableSyntaxOnlyAllows only syntax that can be erased. -
allowImportingTsExtensionsAllows .ts extensions in imports. -
rewriteRelativeImportExtensionsRewrites .ts specifiers on emit. -
resolveJsonModuleAllows importing .json files. -
baseUrlBase directory for non-relative imports. -
pathsAlias patterns for module names. -
rootDir and rootDirsSource root directories. -
types and typeRootsWhich @types packages are included. -
customConditionsExtra package.json export conditions. -
jsxHow JSX is compiled. -
useDefineForClassFieldsClass field semantics. -
experimentalDecoratorsEnables the legacy decorator syntax. -
emitDecoratorMetadataEmits design-time type metadata. -
allowJsIncludes JavaScript files. -
checkJsType-checks JavaScript files. -
maxNodeModuleJsDepthDepth of JavaScript search in node_modules. -
outDir and outFileWhere compiled output goes. -
declaration and declarationDirEmits .d.ts files. -
emitDeclarationOnlyEmits only declarations. -
sourceMap and inlineSourceMapEmits source maps. -
noEmitType-checks without writing files. -
noEmitOnErrorSkips emit when errors exist. -
removeCommentsStrips comments from output. -
importHelpers and noEmitHelpersControls helper functions. -
downlevelIterationAccurate iteration for old targets. -
preserveConstEnumsKeeps const enum declarations.
tsconfig: Projects, Files and Watch Options
-
files, include, excludeChoosing the files in a project. -
extendsInheriting from another tsconfig. -
compilerOptionsThe container for compiler settings. -
compositeEnables project references. -
incremental and tsBuildInfoFileCaches work between runs. -
referencesLinking projects together. -
disableSourceOfProjectReferenceRedirectEditor project reference behavior. -
watchOptionsControls how watch mode watches files. -
typeAcquisitionAutomatic @types download in editors. -
pluginsLanguage service plugins. -
libReplacementReplacing lib files with packages. -
noLib and skipDefaultLibCheckControlling the default library. -
diagnostics and extendedDiagnosticsCompile-time statistics. -
listFiles and listEmittedFilesPrinting the files in a build. -
traceResolutionLogging module resolution. -
explainFilesExplaining why files are included. -
Recommended tsconfig presetsStarter configs for Node, browser and libraries.
The tsc Command Line
-
tscCompiling a project from the command line. -
tsc --initCreating a tsconfig.json. -
tsc -pSelecting a tsconfig file. -
tsc --watchRecompiling on change. -
tsc --buildBuilding project references. -
tsc --noEmitType-checking only. -
tsc --showConfigPrinting the resolved configuration. -
tsc --listFilesListing included files. -
tsc --prettyColorful versus plain diagnostics. -
tsc --help and --allListing every compiler option. -
tsc --versionShowing the compiler version. -
tsc exit codesWhat each exit status means. -
Running TypeScript directlyNode type stripping, tsx and ts-node. -
node --experimental-strip-typesRunning .ts files in Node. -
tsserver and the language serviceHow editors talk to TypeScript. -
Comment directives@ts-expect-error, @ts-ignore and @ts-nocheck.
Error Codes Worth Knowing
-
TS2322Type is not assignable to type. -
TS2339Property does not exist on type. -
TS2345Argument is not assignable to parameter. -
TS2304Cannot find name. -
TS2307Cannot find module or its type declarations. -
TS2531 and TS18047Object is possibly null. -
TS2532 and TS18048Object is possibly undefined. -
TS7006Parameter implicitly has an any type. -
TS7053Element implicitly has an any type. -
TS2741Property is missing in type. -
TS2554Expected N arguments, but got M. -
TS2349This expression is not callable. -
TS2571 and TS18046Object is of type unknown. -
TS2564Property has no initializer. -
TS2367Comparison appears unintentional. -
TS2416Property in type is not assignable to the base type. -
TS2420Class incorrectly implements interface. -
TS2352Conversion of type may be a mistake. -
TS2353Object literal may only specify known properties. -
TS2769No overload matches this call. -
TS2589Type instantiation is excessively deep. -
TS1005Expected token syntax errors. -
TS5023 and TS6046Unknown or invalid compiler options. -
TS2688Cannot find type definition file. -
TS1259 and TS2497Module can only be default-imported with an interop flag. -
TS6133Declared but never used. -
TS2578Unused @ts-expect-error directive.
Concepts and Comparisons
-
Structural typingWhy compatibility depends on shape. -
Type inferenceHow TypeScript works out types for you. -
Widening and narrowingHow literal and union types change. -
Assignability rulesWhen one type can replace another. -
Type erasureWhy types do not exist at run time. -
type versus interfaceWhich one to use and when. -
any versus unknownChoosing the safe escape hatch. -
Enums versus unionsComparing enums, unions and as const objects. -
null and undefinedHandling absence with strict checks. -
Soundness and its limitsWhere TypeScript deliberately allows unsafe code. -
Declaration mergingHow interfaces, namespaces and enums merge. -
Type-level programmingComputing with types, safely. -
Branded typesNominal-like types for IDs and units. -
Runtime validationChecking untrusted data against types. -
Migrating from JavaScriptMoving a codebase to TypeScript step by step. -
Compiler performanceMaking builds and editors faster. -
Linting and formattingESLint, typescript-eslint and Prettier. -
TypeScript versionsWhat changed across recent releases. -
TypeScript 7 native compilerWhat the Go-based compiler changes. -
TypeScript with Node ESMFile extensions, package type and imports. -
Monorepos and project referencesStructuring many packages. -
TypeScript with ReactTyping props, state and events.
Nothing matches โโ. Try the site search.