← All lessons
TypeScript
All TypeScript snippets · 400
Every snippet has its own focus page with an explanation and the output it produces.
Basic Types · 24
- Declaring variables with primitive types
- Typing function parameters with primitives
- Assigning a string to a number variable
- Defining an array of numbers
- Processing a list of user IDs
- Pushing a wrong type to a typed array
- Declaring a fixed-length tuple
- Using a tuple for an HTTP response
- Tuples bypass length checks on push
- Defining a basic numeric enum
- Using an enum for user roles
- Numeric enum reverse mapping at runtime
- Using 'any' to opt out of type checking
- Typing JSON.parse output as unknown
- Attempting to use an 'unknown' type directly
- Typing a function with no return value as void
- Using void in a callback signature
- Returning a value from a void callback
- Assigning null and undefined to variables
- Returning null when a user is not found
- Assigning null to a strict string variable
- Using keyof on tuple types
- Mapping over tuple indices
- Attempting string keyof on a tuple
Variables and Declarations · 14
- Declaring mutable and immutable variables
- Defining API endpoints and retry counts
- Mutating an object property declared with const
- Inferring a number type from assignment
- Inferring object properties
- Inferring a union type from conditional arrays
- Asserting an any variable to a string
- Asserting DOM element types
- Asserting to an incompatible type via unknown
- Type widening of const variables to their literal type
- let and const inside a block
- Scope isolation in a loop
- Accessing var outside of a block
- Type assertion overriding the inferred type
Functions · 15
- Basic function with typed arguments
- Calculating tax with typed numbers
- Returning a string from a number function
- Using a default parameter value
- Sending an email with an optional subject
- Placing a required parameter after an optional one
- Summing values with a rest parameter
- Logging an event with variable tags
- Adding a parameter after a rest parameter
- Basic function overloads for different types
- Padding a string or number differently
- Calling an overload with an unsupported type
- Typing 'this' in an object method
- Enforcing UI element context
- Arrow function inheriting global 'this'
Objects and Interfaces · 15
- Defining and using a simple interface
- Typing a product object
- Adding an excess property to an interface
- Using optional and readonly modifiers
- Defining an immutable user profile
- Attempting to reassign a readonly property
- Passing an exact object literal to an interface
- Failing to pass extra config to a function
- Bypassing excess property checks via variables
- Defining an object with dynamic string keys
- Creating a dynamic string-to-any cache
- Mixing incompatible explicit properties and index signatures
- Extending a base interface
- Extending a BaseUser to create an Admin
- Overriding an inherited property with an incompatible type
Type Aliases vs Interfaces · 9
- Creating a simple type alias
- Defining an object shape with a type alias
- Assigning a boolean to a union type alias
- Comparing type and interface syntax
- Using a type alias for a recursive JSON structure
- Attempting to declare a duplicate type alias
- Defining a constructable type alias
- Dependency injection using constructor types
- Interfaces cannot define constructor signatures
Union and Intersection Types · 9
- Defining a variable that can be string or number
- Formatting a value that can be a string or number
- Calling a method on a union type without narrowing
- Combining two object types with an intersection
- Mixing mixins to create a LoggedUser
- Creating an impossible type intersection
- Defining exact string literals
- Restricting function arguments to specific HTTP methods
- Assigning an invalid literal to a union
Type Guards · 15
- Narrowing a union with typeof
- Processing dynamic input based on typeof
- Using incorrect casing in typeof checks
- Narrowing class instances with instanceof
- Handling specific error subclasses
- Using instanceof on primitive strings
- Narrowing object types with the in operator
- Distinguishing pet capabilities using in
- Checking for optional properties with in
- Creating a custom type predicate function
- Validating and narrowing a Fish object
- A type guard that lies about the actual type
- Narrowing a union based on a literal property
- Handling network state with discriminated unions
- Failing to handle an unreachable case in a discriminated union
Advanced Types · 9
- Defining a string or null union
- Returning null from a failed database lookup
- Accessing properties on a possibly null value
- Safely accessing nested properties with ?.
- Safely accessing a nested user profile
- Using optional chaining vs direct access on null
- Falling back to a default with ??
- Setting a default timeout configuration
- Confusing nullish coalescing with logical OR
Classes · 27
- Defining a simple class with a method
- Creating an invoice entity class
- Accessing a class property before initialization
- Using public, private, and protected modifiers
- Protecting internal state of a bank account
- Accessing a private member from outside the class
- Shorthand property declaration in constructor
- Defining a User DTO with parameter properties
- Missing modifier prefix in parameter properties
- Defining a readonly class property
- Setting a readonly ID in the constructor
- Attempting to reassign a readonly property
- Creating an abstract class with an abstract method
- Defining a base repository with abstract fetch
- Instantiating an abstract class directly
- Using get and set to control access
- Validating an email address on set
- Stack overflow from recursive setter
- Accessing a static class property
- Using a static factory method
- Accessing a static member from an instance
- Implementing an interface
- Extending a base class while implementing an interface
- Extending an interface instead of implementing it
- Initializing static fields in a static block
- Reading a file to initialize static config
- Accessing instance properties in a static block
Generics · 18
- Writing a basic identity function
- Creating a generic API fetcher
- Assuming generic types have specific methods
- Defining a generic box interface
- Defining a generic pagination response
- Using an interface without providing type arguments
- Constraining a generic to have a length property
- Constraining a merge function to object types
- Passing a primitive to a constrained object generic
- Function with two independent type variables
- A generic event emitter mapping
- Mismatching inferred type variables
- Providing a default type parameter
- Defaulting a generic response type
- Default types not applying when explicit type is provided
- Constraining a type by another type parameter
- Type-safe property getter utility
- Passing an invalid key to a keyof constrained function
Utility Types · 24
- Making all properties optional with Partial
- Updating user profiles with patch payloads
- Assuming Required unmakes optional properties during runtime
- Making all properties readonly
- Creating an immutable configuration object
- Mutating a Readonly type via aliasing
- Picking specific properties from an interface
- Creating a preview DTO using Omit
- Omitting a non-existent property
- Creating a string-to-number dictionary
- Mapping status codes to messages
- Missing properties in an exhaustive Record
- Excluding a type from a union
- Extracting only success response types
- Extracting from incompatible unions
- Stripping null and undefined from a type
- Safely getting a value from a cache
- Applying NonNullable to an already non-nullable type
- Extracting the return type of a function
- Extracting the parameters of a callback
- Using ReturnType on an overloaded function
- Unwrapping a Promise type
- Inferring the type of an async API call
- Awaiting a non-Promise type
Mapped Types · 9
- Getting keys of an object as a union
- Restricting function parameters to object keys
- Using keyof on primitive types
- Creating a custom readonly mapped type
- Creating a nullable version of an interface
- Mapped types altering value types incorrectly
- Removing readonly with a mapped type
- Making optional properties required
- Failing to remove optionality at runtime
Conditional Types · 9
- Basic ternary type logic
- Inferring response type based on input
- Distributive nature of conditional types
- Inferring the element type of an array
- Extracting the resolved type of a Promise
- Inferring from a non-matching type
- Filtering types out of a union
- Removing null from a type using distribution
- Preventing distribution with tuple wrapping
Type Compatibility · 12
- Assigning an object with extra properties to a type
- Structural compatibility between two different classes
- Missing required properties in structural typing
- Assigning a function with fewer parameters
- Using a single argument callback in a map
- Assigning a function with more parameters
- Contravariance of function parameters
- Event handler compatibility
- Method bivariance vs strict function types
- Fresh object literal excess property check
- Bypassing fresh object checks via variables
- Excess property check triggered on nested fresh objects
Modern TypeScript · 3
Type Manipulation · 21
- Creating a type from string literals
- Generating event listener names from properties
- Assigning a raw string to a template literal type
- Uppercasing a string literal type
- Creating a constant case from camelCase
- String manipulation utils only work on literal types
- Remapping keys in a mapped type
- Creating a setter interface from a class
- Remapping keys to incompatible types
- Inferring parts of a string literal
- Parsing a route path into parameters
- Failing to infer from a non-matching template
- Filtering out keys using 'as never'
- Creating a public view by stripping private keys
- Failing to remove keys due to incorrect conditional logic
- Constraining an inferred type
- Extracting a specific event type
- infer extends failing the constraint
- Getting the constructor type of a class
- Passing class constructors to functions
- Assigning an instance to a typeof class variable
Modules & Namespaces · 15
- Exporting and importing a typed variable
- Exporting an interface and implementation
- Importing a type without 'type' modifier in isolatedModules
- Defining a default export
- Default exporting a class instance
- Mixing default and named imports incorrectly
- Defining a basic namespace
- Using namespaces for internal utility grouping
- Forgetting to export a namespace member
- Augmenting an existing module interface
- Adding a custom method to Express Request
- Augmenting a module that doesn't exist
- Declaring an ambient module for untyped JS
- Creating a wildcard module declaration
- Importing from an ambient module with missing exports
Decorators · 12
- Applying a basic class decorator
- Injecting metadata into a class
- Decorator returning an invalid type
- Logging method calls with a decorator
- Depracating a method safely
- Losing 'this' context in method decorators
- Basic property decorator
- Registering validation rules via property decorators
- Property decorators cannot intercept initialization
- Marking a parameter with a decorator
- Extracting route parameters via parameter decorators
- Accessing parameter values inside a parameter decorator
Async & Promises · 12
- Defining a function returning a typed Promise
- Fetching user data with typed async/await
- Forgetting to await a Promise
- Awaited type behavior in async functions
- Returning a Promise of a Promise
- Rejecting a Promise with an untyped error
- Typing Promise.all with mixed types
- Fetching parallel resources with Promise.all
- Promise.race returning a union of types
- Try/catch block in async function
- Wrapping API calls in a Result type pattern
- Unhandled promise rejection crashing the app
tsconfig & Compiler · 12
- Enabling strict mode in tsconfig
- Strict null checks preventing undefined access
- Implicit any in function parameters under strict
- Preventing null assignment to strings
- Checking for null before accessing properties
- Array index access returns T instead of T | undefined
- Catching implicit any in variables
- Typing JSON.parse to avoid implicit any
- Implicit any in catch clauses
- Re-exporting types safely under isolatedModules
- Const enums issue with isolatedModules
- Mixing type and value imports under isolatedModules
Advanced Generics · 12
- Array covariance in TypeScript
- Function parameter contravariance
- Unsafe array covariance allowing runtime errors
- Defining a linked list node type
- Typing a deeply nested JSON structure
- Infinite recursion in conditional types
- Inferring only the first type argument
- Failing to infer from nested object properties
- Inferring union types instead of overloads in generics
- Attempting to use class generics in static methods
- Static factory with its own generic parameter
- Accessing static members via a generic instance
Symbols & Iterators · 12
- Declaring a unique symbol
- Using Symbol.iterator to make an object iterable
- Accessing symbol properties with string keys
- Implementing a basic iterator interface
- Custom collection iterator with done state
- Forgetting to return done: true
- Creating a basic generator function
- Generating an infinite sequence lazily
- Typing the return value of a generator
- Using Symbol.for for global symbols
- Cross-module singleton via global symbol
- Comparing local Symbol() with Symbol.for()
Error Handling · 9
- Extending the base Error class
- Adding contextual data to custom errors
- Prototype chain breaking in transpiled ES5 errors
- Catch clause typed as unknown
- Using instanceof to narrow caught errors
- Accessing message property on unknown error
- Throwing a string literal
- Throwing a custom error instance
- TypeScript does not enforce thrown types
Contextual Typing · 4
Inference Deep Dive · 6
Advanced Tuples · 6
Strict Compiler Flags · 9
- Failing to initialize a class property
- Initializing properties via the constructor
- Using the definite assignment assertion operator
- Type-safe usage of call
- Binding a method with correct context and arguments
- Passing wrong types to call under strict mode
- Declaring an unused variable
- Ignoring unused parameters with underscore
- Unused imports triggering errors
Control Flow & Narrowing · 9
- Using never to ensure exhaustive switches
- AssertNever pattern for state machines
- Failing exhaustive check after adding a union member
- Narrowing via switch(true)
- Categorizing values with switch(true)
- Loss of narrowing in non-strict equality
- Storing a type guard in a variable
- Aliasing discriminant checks
- Breaking alias narrowing via reassignment
Advanced Classes & OOP · 9
- Basic mixin application via intersection
- Adding a log method via mixin
- Mixins losing type information of base class
- Typing a function that accepts an abstract class
- Mixin factory accepting abstract base classes
- Directly instantiating an abstract constructor type
- Returning the current class instance type
- Builder pattern using polymorphic this
- Polymorphic this breaking type inference when extracted
Modern ES Features · 6
Advanced Modules · 12
- Typing a dynamic import
- Conditionally loading an analytics module
- Accessing non-existent exports from a dynamic import
- Using import type for interfaces
- Mixing type and value imports inline
- Attempting to use a type-only import as a value
- Default importing a CommonJS module
- Using require in TypeScript
- Namespace import failing without esModuleInterop
- Configuring path mapping in tsconfig
- Importing services using an alias
- Paths not resolving at runtime without bundler
Async Iteration · 6
Type System Limits · 9
- Contrasting any, unknown, and never
- Using never to filter union types
- Assigning values to a never variable
- Deeply nested type instantiation
- Exceeding tuple recursion limits
- Infinite conditional type distribution
- Defining a circular type reference
- JSON schema circular references
- Immediate circular self-reference causing error