Last active
July 8, 2023 10:28
-
-
Save golergka/64b06f711e4cb07c67367bdace79618c to your computer and use it in GitHub Desktop.
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
type AgeBrand = { | |
readonly Age: unique symbol | |
} | |
const Age = t.brand( | |
t.number, // A codec representing the new type, here it's a number | |
(n): n is t.Branded<number, AgeBrand> => n >= 0, // A type guard | |
'Age' // The name of the codec | |
) | |
// Using our brand | |
const result = Age.decode(25) // Right-side Either, since 25 is a valid age | |
if (E.isRight(result)) { | |
const age = result.right // age is of type Age | |
console.log(`Age is ${age > 18 ? 'greater' : 'less'} than 18`) | |
} else { | |
console.log(result.left.map(({ message }) => message).join('\n')) | |
} | |
// Or in a more functional way with fp-ts | |
pipe( | |
20, | |
Age.decode, | |
E.fold( | |
flow( | |
A.map(({ message }) => message), | |
msgs => msgs.join('\n') | |
), | |
(age) => `Age is ${age > 18 ? 'greater' : 'less'} than 18` | |
), | |
console.log | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment