Created
April 20, 2023 09:58
-
-
Save johannschopplich/5d146f20db8b302eec4c0fdb20a2afcb to your computer and use it in GitHub Desktop.
Rust-like result type in TypeScript
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
/** | |
* First, create a type helper that represents | |
* the Result that we'll get from our safe function | |
*/ | |
type Result<T> = | |
| { | |
ok: true; | |
value: T; | |
} | |
| { | |
ok: false; | |
error: unknown; | |
}; | |
/** | |
* Next, make a function that wraps the function | |
* you pass it with a try/catch, then executes it | |
*/ | |
export const makeSafe = | |
<TArgs extends any[], TReturn>(func: (...args: TArgs) => TReturn) => | |
(...args: TArgs): Result<TReturn> => { | |
try { | |
return { | |
value: func(...args), | |
ok: true, | |
}; | |
} catch (e) { | |
return { | |
error: e, | |
ok: false, | |
}; | |
} | |
}; | |
/** | |
* Wrap any function you want to error check with this | |
* makeSafe wrapper | |
*/ | |
const randomlyFail = makeSafe((input: number) => { | |
if (input > 0.5) { | |
throw new Error("oops"); | |
} | |
return { | |
input, | |
}; | |
}); | |
/** | |
* Finally, you can call it - and it'll return the error | |
* if it fails, or the value if it succeeds | |
*/ | |
const result = randomlyFail(0.25); | |
if (result.ok) { | |
result.value; // { input: number } | |
} else { | |
result.error; // unknown | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment