Skip to content

Latest commit

 

History

History

option

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Option<T>

Forget about null and undefined

Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not.

Options can be used as:

  • Initial values
  • Return values for functions that are not defined over their input range
  • Return value for otherwise reporting simple errors, where None is returned on error
  • Optional struct fields
  • Struct fields that can be loaned or “taken”
  • Optional function arguments
  • Nulls
import { None, Some } from "kirka";

const MaybeNumber = Some(3);
MaybeNumber.isSome(); // true
const MaybeNumber = None<number>();
MaybeNumber.isNone(); // false

Create value from option or change type

const MaybeNumber = Some(3); // Some(3)
MaybeNumber.map((v) => v * 4); // Some(12)
MaybeNumber.map((v) => v.toString()); // Some("3")

Take value and leave None in its place

const MaybeNumber = Some(0);
const MaybeString = MaybeNumber.map((v) => "value");
const TakenString = MaybeString.take(); // Some("value")
MaybeString.isNone(); // true
MaybeNumber.isSome(); // true. Because .map() creates clone

Get value from Option

const MaybeNumber = Some(0);
MaybeNumber.unwrap(); // 0

Get value with default from Option

const MaybeNumber = None<number>();
MaybeNumber.orElse(() => 4); // 4
// Same as:
MaybeNumber.unwrapOr(4); // 4
MaybeNumber.or(Some(4)).unwrap(); // 4

Use another Option only if Some

const MaybeString = Some("value"); // Some("value")
MaybeString.and(Some("another")); // Some("another")
MaybeString.and(None()); // None()
const MaybeString = None<string>(); // None()
MaybeString.and(Some("another")); // None()
// Same as:
MaybeString.andThen((value) => None());
MaybeString.andThen((value) => Some("another"));

Compare 2 Options

Some("value") !== Some("value"); // we cannot do this
Some("value").eq(Some("value")); // instead use this method
Some("value").isSomeAnd((v) => v === "value"); // or this

This hints and a more you can just read from IntelliSense (your editor suggestions) or in source code ./interfaces.ts