Created
February 12, 2019 10:25
-
-
Save elnygren/cdd938c9d487e57f75f6553829fe564b to your computer and use it in GitHub Desktop.
Field validation with nice type safety in TypeScript
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
/** 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