Created
February 1, 2025 20:07
-
-
Save eczn/d714cd297e29e7c415dec70066ad9845 to your computer and use it in GitHub Desktop.
TypeScript Option<T>
This file contains hidden or 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
enum TypeNone { } | |
export type None = { type: typeof TypeNone }; | |
function None<T>(d: T): None { return { type: TypeNone } }; | |
function isNone(x: any): x is None { return !!(x && x.type === TypeNone) }; | |
enum TypeSome { } | |
export type Some<T> = { type: typeof TypeSome, data: [_: T] }; | |
function Some<T>(d: T): Some<T> { return { type: TypeSome, data: [d] } }; | |
function isSome(x: any): x is Some<unknown> { return !!(x && x.type === TypeSome && x.data) }; | |
export const Option = { | |
None, isNone, Some, isSome, | |
} | |
export type Option<T> = ( | |
| None | |
| Some<T> | |
); |
This file contains hidden or 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 { Option } from './examples/option.enum'; | |
export function handle(maybe: Option<number>) { | |
if (Option.isSome(maybe)) { | |
const [val] = maybe.data; // val is number | |
return; | |
} | |
maybe // ⬅️ None | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment