Skip to content

Instantly share code, notes, and snippets.

@bonham000
Last active September 28, 2021 13:20
Show Gist options
  • Save bonham000/80fae4eedd1c9ef42d802566f024b432 to your computer and use it in GitHub Desktop.
Save bonham000/80fae4eedd1c9ef42d802566f024b432 to your computer and use it in GitHub Desktop.
TypeScript Snippets
/** ===========================================================================
* TypeScript Result type!
*
* This is a Result type inspired by Rust.
*
* Reference: https://doc.rust-lang.org/rust-by-example/error/result.html
*
* The Result type allow type checking on operations which may fail, since
* in TypeScript there is no way to convey type information in functions which
* may "throw" an error.
* ============================================================================
*/
export interface IOk<T> {
value: T;
error?: undefined;
}
export interface IErr<E> {
error: E;
value?: undefined;
}
/**
* Ok type constructor class.
*/
export class Ok<T> implements IOk<T> {
value: T;
error = undefined;
static of<U>(value: U): Ok<U> {
return new Ok(value);
}
constructor(value: T) {
this.value = value;
}
}
/**
* Err type constructor class.
*/
export class Err<E> implements IErr<E> {
value: undefined;
error: E;
static of<U>(value: U): Err<U> {
return new Err(value);
}
constructor(error: E) {
this.error = error;
}
}
export type Result<T, E> = IOk<T> | IErr<E>;
/**
* Artificially wait the provided amount of time.
*/
export const wait = async (time = 1000) => {
await new Promise((resolve, reject) => setTimeout(resolve, time));
};
/** ===========================================================================
* Inspired by the Result Option type.
*
* https://doc.rust-lang.org/rust-by-example/std/option.html
* ============================================================================
*/
export interface ISome<T> {
value: T;
some: true;
}
export interface INone {
some: false;
}
/**
* Some type constructor class.
*/
export class Some<T> implements ISome<T> {
value: T;
some: true = true;
static of<U>(value: U): Some<U> {
return new Some(value);
}
constructor(value: T) {
this.value = value;
}
}
/**
* None type constructor class.
*/
export class None implements INone {
some: false = false;
static of(): INone {
return new None();
}
}
export type Option<T> = ISome<T> | INone;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment