This library provides a light `Maybe` type for handling optional values, inspired by functional programming languages. A `Maybe` can either be `Just` (containing a value) or `Nothing` (no value).
This library provides a light Maybe type for handling optional values, inspired by functional programming languages. A Maybe can either be Just (containing a value) or Nothing (no value).
Install via npm:
``sh`
npm install perhaps-ts
You can create Maybe instances using the Just and Nothing static methods or helper functions.
`typescript
import { Maybe, Just, Nothing } from "perhaps-ts";
// Using static methods
const maybeValue = Maybe.Just(5);
const noValue = Maybe.Nothing
// Using helper functions
const anotherMaybeValue = Just(10);
const anotherNoValue = Nothing
`
You can check if a Maybe instance has a value (Just) or not (Nothing).
`typescript`
if (maybeValue.IsJust()) console.log("This is Just:", maybeValue.FromJust());
if (noValue.IsNothing()) console.log("This is Nothing");
To retrieve the value of a Just instance, use the FromJust or ToChecked methods. Be cautious as these methods will throw an error if called on a Nothing instance.
`typescript
try {
const value = maybeValue.FromJust();
console.log("Value:", value);
} catch (error) {
console.error(error.message);
}
try {
const value = noValue.ToChecked();
} catch (error) {
console.error(error.message); // Maybe: Attempted to access value of Nothing
}
`
You can provide a default value when dealing with Maybe instances, ensuring you always have a fallback.
`typescript`
const valueOrDefault = noValue.FromMaybe(42);
console.log("Value or Default:", valueOrDefault); // Outputs: 42
You can conditionally extract the value into an output object if the instance is Just.
`typescript`
const output = {};
if (maybeValue.To(output)) {
console.log("Extracted Value:", output.value); // Extracted Value: 5
} else {
console.log("No value to extract");
}
Or you can use the To method with a custom key.
`typescript
type Output = { data?: number };
type UserData = { id: number; name: string };
const output: Output = {};
if (maybeValue.To(output, "data")) {
console.log("Extracted Data:", output.data); // Extracted Data: 5
} else {
console.log("No data to extract");
}
const user: Maybe
const userOutput: Output = {};
if (user.To(userOutput, "data")) {
console.log("Extracted User:", userOutput.data); // Extracted User: { id: 1, name: 'Alice' }
} else {
console.log("No user to extract");
}
`
You can compare Maybe instances for equality.
`typescript
const maybe1 = Just(5);
const maybe2 = Just(5);
const maybe3 = Nothing
console.log(maybe1.equals(maybe2)); // true
console.log(maybe1.equals(maybe3)); // false
console.log(maybe1.notEquals(maybe3)); // true
`
Sure! Here are some examples of how to write functions that return Maybe instead of T | false, along with how to handle and check the returned Maybe values.
Let's write a function that searches for an item in an array and returns a Maybe instead of the item or false.
`typescript
import { Maybe, Just, Nothing } from "maybe-type";
function findItem
for (const item of array) {
if (predicate(item)) {
return Just(item);
}
}
return Nothing
}
// Usage example
const numbers = [1, 2, 3, 4, 5];
const result = findItem(numbers, (n) => n === 3);
if (result.IsJust()) {
console.log("Found:", result.FromJust()); // Found: 3
} else {
console.log("Item not found");
}
`
Here are several ways to handle and check Maybe values returned from functions.
#### Using IsJust and IsNothing
`typescript
const maybeNumber = findItem(numbers, (n) => n === 6);
if (maybeNumber.IsJust()) {
console.log("Found:", maybeNumber.FromJust());
} else {
console.log("Item not found");
}
`
#### Using FromMaybe with a Default Value
`typescript`
const valueOrDefault = maybeNumber.FromMaybe(0);
console.log("Value or Default:", valueOrDefault); // Value or Default: 0
#### Using To for Conditional Extraction
`typescript`
const output = {};
if (maybeNumber.To(output)) {
console.log("Extracted Value:", output.value);
} else {
console.log("No value to extract");
}
Let's create another function that parses an integer from a string and returns Maybe.
`typescript
function parseIntMaybe(input: string): Maybe
const parsed = parseInt(input, 10);
if (isNaN(parsed)) {
return Nothing
}
return Just(parsed);
}
// Usage example
const maybeParsed = parseIntMaybe("123");
if (maybeParsed.IsJust()) {
console.log("Parsed integer:", maybeParsed.FromJust()); // Parsed integer: 123
} else {
console.log("Failed to parse integer");
}
const maybeFailedParsed = parseIntMaybe("abc");
console.log("Parsed or Default:", maybeFailedParsed.FromMaybe(0)); // Parsed or Default: 0
`
Here’s an example of how to use Maybe in an asynchronous function:
`typescript
async function fetchData(url: string): Promise
try {
const response = await fetch(url);
if (!response.ok) {
return Nothing
}
const data = await response.text();
return Just(data);
} catch (error) {
return Nothing
}
}
// Usage example
fetchData("https://api.example.com/data").then((maybeData) => {
if (maybeData.IsJust()) {
console.log("Fetched Data:", maybeData.FromJust());
} else {
console.log("Failed to fetch data");
}
});
`
These examples demonstrate how to use the Maybe type to handle cases where values might be absent, making your code more expressive and robust.
#### Static Methods
- Maybe.Just(value: T): MaybeJust
- Creates a instance containing the provided value.Maybe.Nothing
- Nothing
- Creates a instance with no value.
#### Instance Methods
- IsJust(): booleantrue
- Returns if the instance is Just, otherwise false.IsNothing(): boolean
- true
- Returns if the instance is Nothing, otherwise false.FromJust(): T
- Just
- Returns the value if the instance is , otherwise throws an error.ToChecked(): T
- FromJust
- Alias for .FromMaybe(defaultValue: T): T
- Just
- Returns the value if the instance is , otherwise returns the provided default value.To(out: { [key: string]: T }, key?: string): boolean
- Just
- If the instance is , sets the value in the provided output object and returns true, otherwise returns false. Optionally, you can specify a custom key, otherwise the default key is "value".equals(other: Maybe
- true
- Returns if the other Maybe instance is equal, otherwise false.notEquals(other: Maybe
- true
- Returns if the other Maybe instance is not equal, otherwise false`.
This project is licensed under the MIT License. See the LICENSE file for details.
---
This library simplifies handling optional values in TypeScript, providing a clear and expressive way to manage cases where a value may or may not be present.