Template Literal Types for validating files names
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
Here's Alex using one of my favorite TypeScript features โ Template Literal Types โ to enforce file name conventions in TypeScript.
js
typeImageExtension = `png` | `jp${`e` | ``}g` | `webp`;typeImageFileName = `${Lowercase <string>}.${ImageExtension }`;ยconstgoodName1 :ImageFileName = 'doggy1.jpeg';constgoodName2 :ImageFileName = 'doggy2.jpg';constType '"KittyCat.webp"' is not assignable to type '`${Lowercase<string>}.jpg` | `${Lowercase<string>}.jpeg` | `${Lowercase<string>}.png` | `${Lowercase<string>}.webp`'.2322Type '"KittyCat.webp"' is not assignable to type '`${Lowercase<string>}.jpg` | `${Lowercase<string>}.jpeg` | `${Lowercase<string>}.png` | `${Lowercase<string>}.webp`'.: badName ImageFileName = 'KittyCat.webp';
I just love this feature. Enforcing string patterns with TypeScript makes me feel like a TS pro. ๐
If you enjoyed this article...
Join 5.5k readers and learn something new every week with Web Weekly.
Reply to this post and share your thoughts via good old email.