Created
April 23, 2021 14:59
-
-
Save millsp/fc7162f889673c31829c471b02e05211 to your computer and use it in GitHub Desktop.
Go-style functional type-safe error handling
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
const checkNumber = check((thing: unknown) => { | |
if (typeof thing === 'number') { | |
return thing; | |
} | |
return ko(new E.NOT_NUMBER(thing)); | |
}); | |
const main = check(() => { | |
const [number0, e0] = checkNumber(9); | |
if (caught(number0)) return ko(e0); | |
const [number1, e1] = checkNumber('9'); | |
if (caught(number1)) return ko(e1); | |
}); | |
const E = { | |
NOT_NUMBER: error((v: unknown) => { | |
return `not a valid number ${JSON.stringify(v)}`; | |
}), | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment