Last active
October 7, 2019 21:03
-
-
Save toddlucas/e68fbeb8a59f094c2e4e14e9ab0c8b86 to your computer and use it in GitHub Desktop.
TypeScript Option/Maybe type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If line 7 of the
None
type is changed topublic some?: false = false;
, then{}
also becomes equivalent toNone
. This can make it cleaner and more elegant to returnNone
, but it changes the types of checks that one can perform onMaybe
results. For exampleif (result.some === true)
is still valid, but the converse check forfalse
isn't.