The Optional class is a utility that helps you handle values that may or may not be present. It provides a safer alternative to null checks and improves code readability.
NPM : https://www.npmjs.com/package/node-optional
- of: Creates an
Optionalinstance with a value ornull. - isPresent: Checks if a value is present.
- isOptional: Checks if the value is
null. - get: Retrieves the value if present, throws an error otherwise.
- orElseThrow: Returns the value if present, or throws a custom exception with a message.
Install the package via npm:
npm install optional-classHere’s how to use the Optional class in your TypeScript project:
import Optional from "optional-class";
// Creating an Optional with a value
const optionalValue = Optional.of("Hello, World!");
if (optionalValue.isPresent()) {
console.log(optionalValue.get()); // Output: Hello, World!
}
// Creating an Optional with a null value
const emptyValue = Optional.of(null);
console.log(emptyValue.isOptional()); // Output: true
// Handling a non-present value with a custom exception
try {
emptyValue.orElseThrow(Error, "No value present!");
} catch (e) {
console.error(e.message); // Output: No value present!
}Creates an Optional instance with the provided value. If null is passed, the Optional will represent an empty value.
Returns true if the Optional contains a value, otherwise false.
Returns true if the Optional is empty (i.e., the value is null).
Returns the contained value if present. Throws an error if the value is null.
Returns the value if present. If the value is null, throws the specified exception with the provided message.
This project is licensed under the MIT License.