Last active
July 9, 2025 14:06
-
-
Save NuroDev/061457e0e195dd9f0dd03b7e1f205373 to your computer and use it in GitHub Desktop.
🦺 A minimal `Result` type system for TypeScript
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 { 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 | |
| } |
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
| 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