TypeScript reference
Types, narrowing, generics and compiler settings for safer JavaScript.
TypeScript adds a static type layer to JavaScript. Its value comes from narrowing and from modelling data honestly at boundaries; types disappear at runtime, so runtime validation is still required for untrusted input.
Work through the guided lesson, then test yourself with a challenge.
Open courseBackwards Compatibility
charset
"charset": "value"No longer supported. In early versions, manually set the text encoding for reading files.
Open entryimportsNotUsedAsValues
"importsNotUsedAsValues": "remove"Specify emit/checking behavior for imports that are only used for types.
Open entrykeyofStringsOnly
"keyofStringsOnly": trueMake keyof only return strings instead of string, numbers or symbols. Legacy option.
Open entrynoImplicitUseStrict
"noImplicitUseStrict": trueDisable adding 'use strict' directives in emitted JavaScript files.
Open entrynoStrictGenericChecks
"noStrictGenericChecks": trueDisable strict checking of generic signatures in function types.
Open entryout
"out": "value"Deprecated setting. Use 'outFile' instead.
Open entrypreserveValueImports
"preserveValueImports": truePreserve unused imported values in the JavaScript output that would otherwise be removed.
Open entrysuppressExcessPropertyErrors
"suppressExcessPropertyErrors": trueDisable reporting of excess property errors during the creation of object literals.
Open entrysuppressImplicitAnyIndexErrors
"suppressImplicitAnyIndexErrors": trueSuppress 'noImplicitAny' errors when indexing objects that lack index signatures.
Open entryClasses and modules
abstract class
abstract class ShapeA base class that cannot be instantiated and may declare abstract members subclasses must implement.
Open entryAccess modifiers
public / private / protectedControls compile-time visibility. ECMAScript #private fields provide real runtime privacy.
Open entryClass
class User { … }A constructor with typed fields, methods and access modifiers.
Open entryDeclaration file
declare module "name"Describes types for untyped JavaScript or global APIs in a .d.ts file.
Open entryimplements
class User implements EntityChecks that a class satisfies an interface without inheriting an implementation.
Open entryNamespace import
import * as api from "./api"Imports all named exports as a single object.
Open entryreadonly field
readonly id: stringA field that cannot be reassigned after construction.
Open entryType-only import
import type { User } from "./types"Imports only types so the statement is erased and never creates a runtime dependency.
Open entryCommand-line Options
all
"all": trueShow all compiler options.
Open entryhelp
"help": truePrint this message.
Open entryinit
"init": trueInitializes a TypeScript project and creates a tsconfig.json file.
Open entrylistFilesOnly
"listFilesOnly": truePrint names of files that are part of the compilation and then stop processing.
Open entrylocale
"locale": "value"Set the language of the messaging from TypeScript. This does not affect emit.
Open entryproject
"project": "value"Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.
Open entryshowConfig
"showConfig": truePrint the final configuration instead of building.
Open entryversion
"version": truePrint the compiler's version.
Open entrywatch
"watch": trueWatch input files.
Open entryCompiler and project settings
exactOptionalPropertyTypes
"exactOptionalPropertyTypes": trueSeparates a missing property from a present property whose value is undefined. Stricter and more accurate.
Open entryinclude / exclude
"include": ["app/**/*.ts"]Selects which files the project type-checks.
Open entrylib
"lib": ["ES2022", "DOM"]Declares the built-in APIs available. Without DOM, document and window are unknown to the compiler.
Open entrymoduleResolution
"moduleResolution": "bundler"Matches how the runtime resolves imports. Use bundler for Vite, Nuxt and webpack.
Open entrynoEmit
"noEmit": trueType-checks without writing files, because the bundler handles output.
Open entrynoUncheckedIndexedAccess
"noUncheckedIndexedAccess": trueAdds undefined to index access, forcing you to handle missing keys and holes.
Open entrypaths
"paths": { "@/*": ["./*"] }Rewrites import paths for the compiler and editor. Your bundler must use the same aliases.
Open entryskipLibCheck
"skipLibCheck": trueSkips type-checking declaration files, which speeds builds but can hide dependency conflicts.
Open entrystrict
"strict": trueTurns on the strict family, including strictNullChecks and noImplicitAny. Enable it on every new project.
Open entrytarget
"target": "ES2022"Selects the JavaScript version emitted. Modern targets ship smaller output and rely on evergreen browsers.
Open entryCompiler Diagnostics
diagnostics
"diagnostics": trueOutput compiler performance information after building.
Open entryexplainFiles
"explainFiles": truePrint files read during the compilation including why it was included.
Open entryextendedDiagnostics
"extendedDiagnostics": trueOutput more detailed compiler performance information after building.
Open entrygenerateCpuProfile
"generateCpuProfile": "value"Emit a v8 CPU profile of the compiler run for debugging.
Open entrygenerateTrace
"generateTrace": "value"Generates an event trace and a list of types.
Open entrylistEmittedFiles
"listEmittedFiles": truePrint the names of emitted files after a compilation.
Open entrylistFiles
"listFiles": truePrint all of the files read during the compilation.
Open entrynoCheck
"noCheck": trueDisable full type checking (only critical parse and emit errors will be reported).
Open entrytraceResolution
"traceResolution": trueLog paths used during the 'moduleResolution' process.
Open entryCompiler options
Completeness
Editor Support
Emit
declaration
"declaration": trueGenerate .d.ts files from TypeScript and JavaScript files in your project.
Open entrydeclarationDir
"declarationDir": "value"Specify the output directory for generated declaration files.
Open entrydeclarationMap
"declarationMap": trueCreate sourcemaps for d.ts files.
Open entrydownlevelIteration
"downlevelIteration": trueEmit more compliant, but verbose and less performant JavaScript for iteration.
Open entryemitBOM
"emitBOM": trueEmit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.
Open entryemitDeclarationOnly
"emitDeclarationOnly": trueOnly output d.ts files and not JavaScript files.
Open entryimportHelpers
"importHelpers": trueAllow importing helper functions from tslib once per project, instead of including them per-file.
Open entryinlineSourceMap
"inlineSourceMap": trueInclude sourcemap files inside the emitted JavaScript.
Open entryinlineSources
"inlineSources": trueInclude source code in the sourcemaps inside the emitted JavaScript.
Open entrymapRoot
"mapRoot": "value"Specify the location where debugger should locate map files instead of generated locations.
Open entrynewLine
"newLine": "crlf"Set the newline character for emitting files.
Open entrynoEmitHelpers
"noEmitHelpers": trueDisable generating custom helper functions like '__extends' in compiled output.
Open entrynoEmitOnError
"noEmitOnError": trueDisable emitting files if any type checking errors are reported.
Open entryoutDir
"outDir": "value"Specify an output folder for all emitted files.
Open entryoutFile
"outFile": "value"Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output.
Open entrypreserveConstEnums
"preserveConstEnums": trueDisable erasing 'const enum' declarations in generated code.
Open entryremoveComments
"removeComments": trueDisable emitting comments.
Open entrysourceMap
"sourceMap": trueCreate source map files for emitted JavaScript files.
Open entrysourceRoot
"sourceRoot": "value"Specify the root path for debuggers to find the reference source code.
Open entrystripInternal
"stripInternal": trueDisable emitting declarations that have '@internal' in their JSDoc comments.
Open entryGenerics and utility types
as const
["a", "b"] as constMakes literals readonly and narrow instead of widening to string[].
Open entryAwaited<T>
Awaited<Promise<User>>Unwraps the value type of a promise, recursively.
Open entryGeneric constraint
<T extends { id: string }>Restricts a type parameter so the function can rely on certain members.
Open entryGeneric function
function first<T>(items: T[]): TA type parameter makes a function work with many types while keeping the relationship between inputs and output.
Open entryIndexed access
T[K]Looks up the type of a property by key. Combine it with keyof for type-safe helpers.
Open entrykeyof
keyof TThe union of an object type’s property names. Useful for typed property access.
Open entryParameters<T>
Parameters<typeof fn>A tuple of a function’s parameter types.
Open entryPartial<T>
Partial<User>Makes every property optional. Ideal for patch and update payloads.
Open entryPick<T, K> / Omit<T, K>
Pick<User, "id">Builds a new object type from selected or excluded keys.
Open entryReadonly<T>
Readonly<User>Makes all top-level properties readonly. It is shallow, so nested objects stay mutable.
Open entryRecord<K, V>
Record<"a" | "b", number>Maps a union of keys to a value type. All keys are required by default.
Open entryRequired<T>
Required<User>Makes every property required, the inverse of Partial.
Open entryReturnType<T>
ReturnType<typeof fn>Extracts the return type of a function type. Handy when you cannot import the type directly.
Open entrysatisfies
config satisfies ConfigChecks a value against a type without widening it, so literal details are preserved.
Open entryTemplate literal type
`${string}-${string}`Builds string types from patterns. Useful for event names and keys.
Open entryInterop Constraints
allowSyntheticDefaultImports
"allowSyntheticDefaultImports": trueAllow 'import x from y' when a module doesn't have a default export.
Open entryerasableSyntaxOnly
"erasableSyntaxOnly": trueDo not allow runtime constructs that are not part of ECMAScript.
Open entryesModuleInterop
"esModuleInterop": trueEmit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility.
Open entryforceConsistentCasingInFileNames
"forceConsistentCasingInFileNames": trueEnsure that casing is correct in imports.
Open entryisolatedDeclarations
"isolatedDeclarations": trueRequire sufficient annotation on exports so other tools can trivially generate declaration files.
Open entryisolatedModules
"isolatedModules": trueEnsure that each file can be safely transpiled without relying on other imports.
Open entrypreserveSymlinks
"preserveSymlinks": trueDisable resolving symlinks to their realpath. This correlates to the same flag in node.
Open entryverbatimModuleSyntax
"verbatimModuleSyntax": trueDo not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting.
Open entryJavaScript Support
allowJs
"allowJs": trueAllow JavaScript files to be a part of your program. Use the 'checkJs' option to get errors from these files.
Open entrycheckJs
"checkJs": trueEnable error reporting in type-checked JavaScript files.
Open entrymaxNodeModuleJsDepth
"maxNodeModuleJsDepth": 1Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'.
Open entryLanguage and Environment
emitDecoratorMetadata
"emitDecoratorMetadata": trueEmit design-type metadata for decorated declarations in source files.
Open entryexperimentalDecorators
"experimentalDecorators": trueEnable experimental support for legacy experimental decorators.
Open entryjsx
"jsx": "preserve"Specify what JSX code is generated.
Open entryjsxFactory
"jsxFactory": "value"Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'.
Open entryjsxFragmentFactory
"jsxFragmentFactory": "value"Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'.
Open entryjsxImportSource
"jsxImportSource": "value"Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'.
Open entrylibReplacement
"libReplacement": trueEnable lib replacement.
Open entrymoduleDetection
"moduleDetection": "auto"Control what method is used to detect module-format JS files.
Open entrynoLib
"noLib": trueDisable including any library files, including the default lib.d.ts.
Open entryreactNamespace
"reactNamespace": "value"Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit.
Open entryuseDefineForClassFields
"useDefineForClassFields": trueEmit ECMAScript-standard-compliant class fields.
Open entryModules
allowArbitraryExtensions
"allowArbitraryExtensions": trueEnable importing files with any extension, provided a declaration file is present.
Open entryallowImportingTsExtensions
"allowImportingTsExtensions": trueAllow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set.
Open entryallowUmdGlobalAccess
"allowUmdGlobalAccess": trueAllow accessing UMD globals from modules.
Open entrybaseUrl
"baseUrl": "value"Specify the base directory to resolve non-relative module names.
Open entrycustomConditions
"customConditions": []Conditions to set in addition to the resolver-specific defaults when resolving imports.
Open entrymodule
"module": "none"Specify what module code is generated.
Open entrymoduleSuffixes
"moduleSuffixes": []List of file name suffixes to search when resolving a module.
Open entrynoResolve
"noResolve": trueDisallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project.
Open entrynoUncheckedSideEffectImports
"noUncheckedSideEffectImports": trueCheck side effect imports.
Open entryresolveJsonModule
"resolveJsonModule": trueEnable importing .json files.
Open entryresolvePackageJsonExports
"resolvePackageJsonExports": trueUse the package.json 'exports' field when resolving package imports.
Open entryresolvePackageJsonImports
"resolvePackageJsonImports": trueUse the package.json 'imports' field when resolving imports.
Open entryrewriteRelativeImportExtensions
"rewriteRelativeImportExtensions": trueRewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files.
Open entryrootDir
"rootDir": "value"Specify the root folder within your source files.
Open entryrootDirs
"rootDirs": []Allow multiple folders to be treated as one when resolving modules.
Open entrytypeRoots
"typeRoots": []Specify multiple folders that act like './node_modules/@types'.
Open entrytypes
"types": []Specify type package names to be included without being referenced in a source file.
Open entryNarrowing and unions
Assertion function
asserts value is UserA function that throws when a condition fails and therefore narrows for the caller.
Open entryDiscriminated union
type Shape = { kind: "circle"; r: number } | …A shared literal field lets TypeScript narrow the whole object in a switch.
Open entryExhaustive switch
const _never: never = valueA never assignment in the default branch makes the compiler flag any unhandled union member.
Open entryin operator
if ("id" in value)Narrows by checking whether a property exists on the value.
Open entryinstanceof guard
if (error instanceof Error)Narrows to a class at runtime. Catch values are unknown because anything can be thrown.
Open entryNon-null assertion
value!Tells the compiler a value is not null. It performs no runtime check, so use it only when the fact is guaranteed.
Open entryType assertion
value as ShapeOverrides inference. Prefer narrowing or validation; assertions can hide real bugs.
Open entryType predicate
function isUser(v: unknown): v is UserA user-defined guard that teaches TypeScript how a function narrows its argument.
Open entrytypeof guard
if (typeof value === "string")Narrows primitives at runtime. TypeScript understands the guard in the same scope.
Open entryUnion type
string | numberA value that may be one of several types. Narrow before calling type-specific methods.
Open entryOutput Formatting
noErrorTruncation
"noErrorTruncation": trueDisable truncating types in error messages.
Open entrypreserveWatchOutput
"preserveWatchOutput": trueDisable wiping the console in watch mode.
Open entrypretty
"pretty": trueEnable color and formatting in TypeScript's output to make compiler errors easier to read.
Open entryProjects
composite
"composite": trueEnable constraints that allow a TypeScript project to be used with project references.
Open entrydisableReferencedProjectLoad
"disableReferencedProjectLoad": trueReduce the number of projects loaded automatically by TypeScript.
Open entrydisableSolutionSearching
"disableSolutionSearching": trueOpt a project out of multi-project reference checking when editing.
Open entrydisableSourceOfProjectReferenceRedirect
"disableSourceOfProjectReferenceRedirect": trueDisable preferring source files instead of declaration files when referencing composite projects.
Open entryincremental
"incremental": trueSave .tsbuildinfo files to allow for incremental compilation of projects.
Open entrytsBuildInfoFile
"tsBuildInfoFile": "value"Specify the path to .tsbuildinfo incremental compilation file.
Open entryType Checking
allowUnreachableCode
"allowUnreachableCode": trueDisable error reporting for unreachable code.
Open entryallowUnusedLabels
"allowUnusedLabels": trueDisable error reporting for unused labels.
Open entryalwaysStrict
"alwaysStrict": trueEnsure 'use strict' is always emitted.
Open entrynoFallthroughCasesInSwitch
"noFallthroughCasesInSwitch": trueEnable error reporting for fallthrough cases in switch statements.
Open entrynoImplicitAny
"noImplicitAny": trueEnable error reporting for expressions and declarations with an implied 'any' type.
Open entrynoImplicitOverride
"noImplicitOverride": trueEnsure overriding members in derived classes are marked with an override modifier.
Open entrynoImplicitReturns
"noImplicitReturns": trueEnable error reporting for codepaths that do not explicitly return in a function.
Open entrynoImplicitThis
"noImplicitThis": trueEnable error reporting when 'this' is given the type 'any'.
Open entrynoPropertyAccessFromIndexSignature
"noPropertyAccessFromIndexSignature": trueEnforces using indexed accessors for keys declared using an indexed type.
Open entrynoUnusedLocals
"noUnusedLocals": trueEnable error reporting when local variables aren't read.
Open entrynoUnusedParameters
"noUnusedParameters": trueRaise an error when a function parameter isn't read.
Open entrystrictBindCallApply
"strictBindCallApply": trueCheck that the arguments for 'bind', 'call', and 'apply' methods match the original function.
Open entrystrictBuiltinIteratorReturn
"strictBuiltinIteratorReturn": trueBuilt-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'.
Open entrystrictFunctionTypes
"strictFunctionTypes": trueWhen assigning functions, check to ensure parameters and the return values are subtype-compatible.
Open entrystrictNullChecks
"strictNullChecks": trueWhen type checking, take into account 'null' and 'undefined'.
Open entrystrictPropertyInitialization
"strictPropertyInitialization": trueCheck for class properties that are declared but not set in the constructor.
Open entryuseUnknownInCatchVariables
"useUnknownInCatchVariables": trueDefault catch clause variables as 'unknown' instead of 'any'.
Open entryTypes and shapes
any
value: anyDisables type checking. Treat it as an escape hatch that should not cross module boundaries.
Open entryArray types
string[] / Array<string>Declares an array of a single element type. Readonly<string[]> prevents mutation.
Open entryenums
enum Role { Admin, Learner }Named constants. Prefer union literals for new code because enums add runtime objects.
Open entryFunction type
(a: number) => stringDescribes a function signature, including parameters and return type.
Open entryInterface
interface User { … }Describes an object shape. Interfaces can be extended and declared twice; type aliases cannot.
Open entryLiteral type
type Direction = "up" | "down"Restricts a value to exact literals. Perfect for options, states and event names.
Open entrynever
neverThe type of a value that cannot happen, or of a function that never returns normally.
Open entrynull and undefined
string | nullWith strictNullChecks, null and undefined are separate types and must be handled explicitly.
Open entryOptional property
name?: stringThe property may be missing or undefined. Do not use it for values that are always present but sometimes empty.
Open entryReadonly
readonly id: stringPrevents reassignment of the property after creation. It is shallow and checked only by the compiler.
Open entryRecord
Record<string, number>An object whose keys and values share types.
Open entryTuple
[string, number]A fixed-length array where each position has a type. Optional and rest elements are allowed.
Open entryType alias
type User = { id: string }Gives a name to any type, including unions and tuples. Aliases are erased at build time.
Open entryType annotation
const name: string = "Ada";Declares the expected type of a value. Inference usually means you only annotate boundaries.
Open entryunknown
value: unknownA safe alternative to any: you must narrow before using the value.
Open entryvoid
function log(): voidThe return type for functions that do not return a value. A void callback may ignore any return value.
Open entryWatch and Build Modes
Turn the reference into recall.
Read the full lesson, then solve the challenge without looking. That is where the knowledge sticks.