91 entries · 7 categories
TypeScript reference
Basic types, interfaces, unions, generics and every utility type. Each example shows the type the compiler infers.
91 entries
Basic types
Primitive types, arrays, tuples, enums, any, unknown and never.
- string, number, booleanThe basic primitive types: text, numbers, and boolean values.
- Arrays: number[] and Array<T>Array types, where every element has the same type.
- TuplesFixed-length arrays where each position has its own type.
- enumA named set of constant values, either numbers or strings.
- anyThe type that turns off checking: the value can be anything.
- unknownThe safe counterpart to any: a value of an unknown type that you must check before use.
- neverThe type of a value that never occurs: functions that don’t end normally, and impossible cases.
- voidThe return type of functions that return nothing.
- null and undefinedThe types for the absence of a value, controlled by strictNullChecks.
- Literal typesTypes that allow only specific values, e.g. "easy" | "hard".
- Object typesA description of an object’s shape: what fields it has and of what type.
- Function typesTyping parameters, the return value, and functions themselves as values.
- Type inferenceThe compiler figuring out types automatically, without you writing annotations.
Interfaces and classes
Describing the shape of objects, inheritance and access modifiers.
- interfaceA named description of an object’s shape that you can extend and merge.
- typeA type alias: a name for any type, including unions, tuples, and complex types.
- Optional properties (?)Properties that may, but don’t have to, show up in an object.
- readonlyA modifier that blocks changing a field after the object is created.
- Index signatureA description of objects with arbitrary keys and values of one type.
- extends (interfaces)Extending an interface with new fields, based on an existing one.
- implementsA declaration that a class fulfills the contract described by an interface.
- public, private, protectedAccess modifiers that control where a class’s fields and methods can be used from.
- abstract classA base class you can’t create directly, with methods for its descendants to fill in.
- Function overloadsSeveral signatures for one function: the result type depends on which arguments you call it with.
- DecoratorsFunctions attached with an @ sign to classes and their members, which extend or change their behavior.
- declare and .d.ts filesDescribing the types of something that exists outside your TypeScript code: global variables, JavaScript libraries, and modules.
Unions and narrowing
Combining types, type guards, assertions and satisfies.
- Union (A | B)A type that can be one of several types.
- Intersection (A & B)A type that combines all the fields of several types at once.
- Type narrowingDetermining a more precise type for a value based on checks in your code.
- Type guards (value is T)Custom checking functions that narrow the type at the call site.
- Discriminated unionsUnions of objects with a shared tag field that makes it easy to tell the variants apart.
- typeof (in types)Gets the type of a variable or value so you can use it somewhere else.
- instanceofNarrows the type to a class by checking whether the object was created by it.
- The in operatorNarrows a union of objects by checking whether an object has a given property.
- Type assertion (as)Telling the compiler the type of a value when you know more than it does.
- satisfiesChecks that a value matches a type without changing the inferred type.
- as constFreezes literals in an expression: the narrowest types and read-only fields.
- Non-null assertion (!)An exclamation mark after an expression removes null and undefined from the type without checking.
- import typeA type-only import that disappears completely from the generated JavaScript.
- usingA declaration of a resource that is released automatically when the block exits, even after an error.
- this as a typeThe this type means the object a method was called on, and the this parameter describes the context of a regular function.
Generics and advanced types
Types with parameters, keyof, conditional, mapped and template literal types.
- Generics <T>Types and functions with a type parameter that work for many types without losing precision.
- Generic constraints (extends)Requiring a type parameter to match a specific shape.
- keyofCreates a union of the key names of a given object type.
- Indexed access types T[K]Retrieves the type of a field from another type, just like reading a property from an object.
- Conditional typesTypes chosen based on a condition: T extends U ? X : Y.
- inferPulls a type out from inside another type, within a conditional type.
- Mapped typesCreate a new object type by transforming every key of another type.
- Template literal typesString types built from templates, like `${A}-${B}`.
- Default type parametersThe value a type parameter takes when it isn’t provided or inferred.
Utility types
Built-in types that transform other types: Partial, Pick, Omit and the rest.
- Partial<Type>Creates a type where every property is optional.
- Required<Type>Creates a type where every property is required.
- Readonly<Type>Creates a type where every property is read-only.
- ReadonlyArray<Type>A read-only array: no push, sort, or assignment by index.
- Pick<Type, Keys>Creates a type containing only selected properties of another type.
- Omit<Type, Keys>Creates a type without selected properties of another type.
- Record<Keys, Type>Creates an object type with given keys, where every value has the same type.
- Exclude<UnionType, ExcludedMembers>Removes from a union the types that match a given type.
- Extract<Type, Union>Keeps in a union only the types that match a given type.
- NonNullable<Type>Removes null and undefined from a type.
- ReturnType<Type>Gets the type of the value a function returns.
- Parameters<Type>Gets the types of a function’s parameters as a tuple.
- Awaited<Type>Gets the type of the value that awaiting a promise produces.
- InstanceType<Type>Gets the type of the object a class constructor creates.
- ConstructorParameters<Type>Gets the types of a class constructor’s parameters as a tuple.
- Uppercase, Lowercase, Capitalize, UncapitalizeBuilt-in types that change letter case in text types, e.g. "gold" to "GOLD".
- NoInfer<Type>Blocks inferring a type parameter from a given spot, so other arguments determine the type.
tsconfig options
The most important compiler options in tsconfig.json.
- "strict"Turns on a set of the most important, rigorous compiler checks.
- "target"The JavaScript version the compiler turns your code into.
- "lib"Selects the built-in environment types: the JavaScript version, browser APIs, and individual new language features.
- "jsx"Specifies what the compiler does with JSX syntax in .tsx files.
- "module"The module format of the generated code and how imports are understood.
- "moduleResolution"The algorithm the compiler uses to find the files named in imports.
- "paths"Path aliases in imports, e.g. @/components instead of ../../components.
- "noImplicitAny"Reports an error when the compiler would have to silently assume the any type.
- "strictNullChecks"Treats null and undefined as separate types, forcing you to handle them.
- "noUncheckedIndexedAccess"Adds undefined to the type of an index read, because an element at that index may not exist.
- "esModuleInterop"Makes it easier to import CommonJS packages with ES module syntax.
- "verbatimModuleSyntax"Imports without the word type stay in JavaScript unchanged, so type imports must be marked explicitly.
- "isolatedModules"Makes sure every file can be translated to JavaScript on its own, without knowing about the rest of the project.
- "outDir" and "rootDir"The folder where compiled code goes, and the folder of the sources.
- "declaration"Generates .d.ts files with types next to the compiled JavaScript.
- "sourceMap"Generates .js.map source maps, so the debugger shows your TypeScript code instead of the generated JavaScript.
- "include" and "exclude"Which files the compiler takes into account, and which it skips.
- "skipLibCheck"Skips error checking in .d.ts declaration files, which speeds up compilation.
Comparisons
How similar types and constructs differ and when to pick each one.
- interface vs typeinterface describes an object’s shape and can be extended or merged with another declaration of the same name, while type aliases any type, including unions and tuples.
- any vs unknownany turns off type checking and allows anything, while unknown also accepts any value but requires a type check before you can use it.
- enum vs unionenum creates a named set of constants that also exists at runtime as an object, while a literal union is just a type, lighter and with no JavaScript code at all.
- Pick vs OmitPick<Type, Keys> selects only the given fields from a type, while Omit<Type, Keys> copies every field except the given ones.
- as vs satisfiesas tells the compiler to trust your type and check nothing, while satisfies checks that the value matches the type and keeps the exact type inferred from the value.
- extends vs implementsextends inherits fields and code from a base class, while implements only forces a class to have an interface’s methods and fields, without any of its code.
- void vs nevervoid means a function returns no useful value, while never means a function never returns at all: it throws an error or runs forever.