Last active
May 1, 2023 22:52
-
-
Save mikehadlow/65347bade6210c73e216c58e183d7c60 to your computer and use it in GitHub Desktop.
Simple monadic 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
// Result | |
type Success<S> = { success: true, value: S } | |
type Failure<F> = { success: false, message: F } | |
type Bindable<S, F> = { | |
bind: <B,>(func: (input: S) => Result<B, F>) => Result<B, F> | |
} | |
type Result<S, F> = (Success<S> | Failure<F>) & Bindable<S, F> | |
const toResult = <S, F>(input: S): Result<S, F> => ({ | |
success: true, | |
value: input, | |
bind: func => func(input) | |
}) | |
const toFailure = <S, F>(message: F): Result<S, F> => ({ | |
success: false, | |
message: message, | |
bind: _ => toFailure(message) | |
}) | |
// Let's try it out... | |
const isEven = (input: number): Result<number, string> => { | |
if(input % 2 === 0) { | |
return toResult(input) | |
} | |
return toFailure("Not even!") | |
} | |
const divisibleBy3 = (input: number): Result<number, string> => { | |
if(input % 3 === 0) { | |
return toResult(input) | |
} | |
return toFailure("Not divisible by 3!") | |
} | |
const testWith = (input: number): void => { | |
const inputResult = toResult<number, string>(input) | |
const result = inputResult.bind(isEven).bind(divisibleBy3) | |
if(result.success) { | |
console.log(`${input} Success: ${result.value}`) | |
} else { | |
console.log(`${input} Failure: ${result.message}`) | |
} | |
} | |
const main = () => { | |
testWith(6) | |
testWith(8) | |
testWith(9) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Link to Typescript Playground:
https://www.typescriptlang.org/play?#code/PTAECUFMGcFcBsAuBYAUGxBPADpUBlWAYyJmgB58A+UAXlAG9Q4SyAuURAJ1kgBpQANwCG8Xh3ygAvhhx4AYsICWYrpHLya9Ji1LRoHAGajo-UAFsywgOaQO86Wlm5QAISUA7ACbCARvHV8AU06RjRQUF9PLw5yVz4qAApDWA8iDkTPbFhECQBKOhooOCQ44KoC2iKYBEQy0E00GXRULBdi2spy0MTCVn1KGgAfBuVVdU0CgDI3aL8AroaqJ1QiAHsPaERONY6kUMXNTI9s3II8jj26oKXC0ESGcOZiPQNOHn4nkTE7UCycvhPKLeWLxJIpNIZY6nfJ3K71SYXCA1UrxW5VUAQojQnJ5Jp4lrrTbbRBrRQqWBqA43I6WfQ2X7yJHwmlaGgPJ66diYkyfVAROnQBkcQUMwH8yLRUEJRIAfSh-zO+Eq1RKdTRiMuKPV3QxpPJ40SotsBKkBLQIFAABlIIgAOTQd6YP7bNY5AB0npWRK2f2gAFFBJAPD1FRwPLBzL5IFxmdryBGozGBFsuJ5rGywhKlIYcdsAKSgABMdFo9AADAVHhKImpEJSQ6SrnmCRFmrXbQ2dgbKZBEgAiABya22kCDHgAhP3Td6Nr6vEpBEpoEp-JBXJgAMyhk45cOR6OxrVqhMH5PMbjpzPViI5vOgQvbssVqtPDv1riN3baltPdugOsu31MZewHYdtgXJcVzXSJnU3KcZ0JOcSRgRAAHUlEQAALHcYVARNDyRQQ1iULw7hvUAfW2RUrlCJt4wI89UyvX8WgiKiAO1UIaO1d1gS8TIA3HPI+OiRJIOXVcAg3TdzWzXM1DVd0uX0V8a0ouc1gCd14DWaxEgAAwAEgYRUpAIF5uRMxTandb5eCkAzW2kUBIHgUwswidjNO03T9OM0zd0QcyezUDhrN441IEc5zmmaNAOPMZQQ3oRIVU8zhUIw7DEgANmcxAsswrDEgADgKoqcoATkQtAks8NKgA