Sum types
Goal: Model alternatives with tagged variants instead of booleans + fields.
Sum types compose: type Result<T, E> = Ok(T) | Err(E) (see @superjs/std-core).
Example
type Result<T, E> = Ok(T) | Err(E)
function divide(a: number, b: number): Result<number, string> {
if (b === 0) return Err("divide by zero")
return Ok(a / b)
}
function run(): void {
const r: Result<number, string> = divide(10, 2)
match r {
Ok(n) => console.log(n),
Err(e) => console.log(e),
}
}Key takeaways
- Variants carry payloads:
Some(42),None. - Prefer
Resultover thrown exceptions for expected errors. - Import helpers from
@superjs/std-corein real projects.
Next: Object types