Represents an optional value that may or may not exist.
Maybe is a type-safe way to handle nullable values without using null or undefined directly. A Maybe is either Just (contains a value) or Nothing (empty).
This pattern eliminates null errors by forcing you to explicitly handle the absence of a value at compile time.
Example 1
Example 1
// Basic usage function findUser(id: string): Maybe<User> { const user = users.get(id) return Maybe.FromNullable(user) } const result = findUser('123') result.matchWith({ Just: (user) => console.log(`Found: ${user.name}`), Nothing: () => console.log('User not found') })
Transforms the Just value using a function that returns a Maybe (also known as flatMap).
Similar to map, but the handler function returns a Maybe instead of a plain value. This is useful for chaining operations that may themselves return Nothing, avoiding nested Maybes.
Gets the Just value or returns a default value if this is Nothing.
This provides a simple way to extract a value from a Maybe with a fallback, without needing to use pattern matching.
getOrThrow(error?: string): Type
Extracts the value from a Just or throws an error if it's Nothing.
Warning: This method throws exceptions and should be used sparingly. Prefer getOrElse or matchWith for safer error handling.
Transforms the Just value using the provided function.
If the Maybe is Just, applies the handler to the value and returns a new Just Maybe. If the Maybe is Nothing, returns Nothing without calling the handler.
This allows you to chain transformations on present values while automatically propagating Nothing.
matchWith<JustReturnType,NothingReturnType,>(pattern: { Just: (value: NonNullable<Type>) => JustReturnType; Nothing: () => NothingReturnType; }): JustReturnType | NothingReturnType
Pattern matches on the Maybe, executing different handlers for Just and Nothing cases.
This is the primary way to extract values from a Maybe. Both cases must be handled, ensuring you never forget to handle the absence of a value.
Returns this Maybe if it's Just, otherwise calls the handler to provide an alternative.
This allows you to provide an alternative Maybe when this one is Nothing, useful for trying fallback operations or providing computed defaults.
FromNullable<Type>(value: Nullable<Type>): Maybe<Type>
Converts a nullable value into a Maybe.
This is the primary way to create Maybe values from existing code that uses null or undefined. If the value is null or undefined, returns Nothing. Otherwise, returns Just with the value.
HasInstance<Type>(value: unknown): value is Maybe<Type>
Type guard to check if a value is a Maybe instance.
Creates a Maybe containing a value.
Use this when you have a value that definitely exists and want to wrap it in a Maybe for use with other Maybe-returning functions.