A familiar shape
Every codebase I've worked in has had a validation function that looks roughly like this:
interface ValidationResult { valid : boolean ; error ?: string ; data ?: File ; }
function validateFile ( file : File ): ValidationResult { if ( file . size > MAX_SIZE ) { return { valid : false , error : ' File too large ' }; } if ( ! ALLOWED_EXTENSIONS . includes ( getExtension ( file . name ))) { return { valid : false , error : ' Invalid file type ' }; } return { valid : true , data : file }; }
Enter fullscreen mode
Exit fullscreen mode
And every codebase has consumers like this:
const result = validateFile ( uploadedFile ); if ( result . valid ) { uploadToS3 ( result . data ! ); }
Enter fullscreen mode
Exit fullscreen mode
That ! non-null assertion at the end is the tell. The type system doesn't know that data is guaranteed to exist when valid is true. The consumer has to assert it.…