Skip to content

Instantly share code, notes, and snippets.

@golergka
Last active July 8, 2023 10:28
Show Gist options
  • Save golergka/64b06f711e4cb07c67367bdace79618c to your computer and use it in GitHub Desktop.
Save golergka/64b06f711e4cb07c67367bdace79618c to your computer and use it in GitHub Desktop.
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