Menu

Post image 1
Post image 2
1 / 2
0

Type Your File Validation Library as a Security Boundary

DEV Community·venkatesh m·19 days ago
#Ja6feQEs
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More