Skip to content

Instantly share code, notes, and snippets.

@ryangjchandler
Created September 16, 2021 13:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryangjchandler/7363b254b8866f8310413308599d01d6 to your computer and use it in GitHub Desktop.
Save ryangjchandler/7363b254b8866f8310413308599d01d6 to your computer and use it in GitHub Desktop.
Typescript Optional<T> type (Rust-esque)
type Option<T> = Some<T> | None<T>;
interface Optional<T> {
unwrap(): T;
unwrapOr(or: T): T;
isSome(): boolean;
isNone(): boolean;
}
class Some<T> implements Optional<T> {
constructor(private value: T) {}
unwrap(): T {
return this.value
}
unwrapOr(or: T): T {
return this.unwrap();
}
isSome(): boolean {
return true
}
isNone(): boolean {
return false
}
}
class None<T> implements Optional<T> {
unwrap(): never {
throw new ReferenceError('Attempt to call `unwrap()` on `None` value.')
}
unwrapOr(or: T): T {
return or
}
isSome(): boolean {
return false;
}
isNone(): boolean {
return true;
}
}
function expectsOptional(value: Option<string>) {
if (value.isSome()) {
console.log(`Some: ${value.unwrap()}`)
} else {
console.log(`None`)
}
}
expectsOptional(new Some("Hello!"))
expectsOptional(new None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment