| title | Understand the Option Data Type | |||||
|---|---|---|---|---|---|---|
| id | data-option | |||||
| skillLevel | beginner | |||||
| applicationPatternId | core-concepts | |||||
| summary | Use Option<A> to explicitly represent a value that may or may not exist, eliminating null and undefined errors. | |||||
| tags |
|
|||||
| rule |
|
|||||
| related |
|
|||||
| author | PaulJPhilp | |||||
| lessonOrder | 16 |
Use the Option<A> data type to represent values that may or may not exist.
This eliminates the need for null or undefined, making absence explicit and type-safe.
Option makes it impossible to forget to handle the "no value" case.
It improves code safety, readability, and composability, and is a foundation for robust domain modeling.
import { Option } from "effect";
// Create an Option from a value
const someValue = Option.some(42); // Option<number>
const noValue = Option.none(); // Option<never>
// Safely convert a nullable value to Option
const fromNullable = Option.fromNullable(Math.random() > 0.5 ? "hello" : null); // Option<string>
// Pattern match on Option
const result = someValue.pipe(
Option.match({
onNone: () => "No value",
onSome: (n) => `Value: ${n}`,
})
); // string
// Use Option in a workflow
function findUser(id: number): Option.Option<{ id: number; name: string }> {
return id === 1 ? Option.some({ id, name: "Alice" }) : Option.none();
}Explanation:
Option.some(value)represents a present value.Option.none()represents absence.Option.fromNullablesafely lifts nullable values into Option.- Pattern matching ensures all cases are handled.
Using null or undefined to represent absence, or forgetting to handle the "no value" case, which leads to runtime errors and less maintainable code.