Skip to content

Instantly share code, notes, and snippets.

@toddlucas
Last active October 7, 2019 21:03
Show Gist options
  • Save toddlucas/e68fbeb8a59f094c2e4e14e9ab0c8b86 to your computer and use it in GitHub Desktop.
Save toddlucas/e68fbeb8a59f094c2e4e14e9ab0c8b86 to your computer and use it in GitHub Desktop.
TypeScript Option/Maybe type
export class Some<T> {
public some: true = true;
constructor(public value: T) { }
}
export class None {
public some: false = false;
}
export type Maybe<T> = Some<T> | None;
import { Maybe, None, Some } from "./maybe";
function safeParseInt(val: string): Maybe<number> {
const num = parseInt(val, 10);
if (isNaN(num)) {
// Can also return { some: false } here.
return new None();
}
return new Some(num);
}
function displayInt(val: string) {
const result = safeParseInt(val);
if (result.some) {
// With the above type guard, `result` is `Some<int>` here.
console.log(result.value);
} else {
// The `result` object is `None` here.
console.error("Value is not a number.");
}
}
@toddlucas
Copy link
Author

Inspired by Josh Wulf

@toddlucas
Copy link
Author

If line 7 of the None type is changed to public some?: false = false;, then {} also becomes equivalent to None. This can make it cleaner and more elegant to return None, but it changes the types of checks that one can perform on Maybe results. For example if (result.some === true) is still valid, but the converse check for false isn't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment