Skip to content

Instantly share code, notes, and snippets.

@elnygren
Created February 12, 2019 10:25
Show Gist options
  • Save elnygren/cdd938c9d487e57f75f6553829fe564b to your computer and use it in GitHub Desktop.
Save elnygren/cdd938c9d487e57f75f6553829fe564b to your computer and use it in GitHub Desktop.
Field validation with nice type safety in TypeScript
/** Valid doesn't really need any metadata */
type Valid = {
t: true
}
/** Invalid should describe all the problems */
type Invalid = {
t: false
errors: Array<{ text: string /** object, in case more fields are needed here */ }>
}
/** Field validator signature */
type ValidateField<T> = (input: T) => Valid | Invalid
/** implementation of string validator */
const validateTitle: ValidateField<string> = input => {
return input
? { t: true }
: {
t: false,
errors: [
{ text: 'Too long error, do something about it' },
{ text: 'Value should be funnier' },
{ text: 'lol asd asd asd asd asd asda sd' },
],
}
}
// render example
const valid = validateTitle('foo')
if (valid.t) {
// foo
valid.errors.map // compiler error here!
} else {
const items = valid.errors.map(x => x.text)
// <ul>{items}</ul>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment