Skip to content

Instantly share code, notes, and snippets.

@NuroDev
Last active July 9, 2025 14:06
Show Gist options
  • Save NuroDev/061457e0e195dd9f0dd03b7e1f205373 to your computer and use it in GitHub Desktop.
Save NuroDev/061457e0e195dd9f0dd03b7e1f205373 to your computer and use it in GitHub Desktop.
🦺 A minimal `Result` type system for TypeScript
import { Err, Ok, PromiseResult } from 'path/to/module';
interface User {
// ...
}
enum UserError {
USER_NOT_FOUND = 'USER_NOT_FOUND',
}
async function getUser(id: string): PromiseResult<User, { type: UserError }> {
const user = await db.query(`SELECT * FROM users WHERE id = ?`, [id]);
if (!user) return Err({ type: UserError.USER_NOT_FOUND });
return Ok(user);
}
const result = await getUser("123");
if (result.ok) {
console.log(result.value);
// ^? User
}
export type Result<T, E> =
| {
ok: true;
value: T;
}
| {
ok: false;
error: E;
};
export type PromiseResult<T, E> = Promise<Result<T, E>>;
export const Ok = <T, E>(value: T): Result<T, E> => ({
ok: true,
value,
});
export const Err = <T, E>(error: E): Result<T, E> => ({
ok: false,
error,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment