This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
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. 😅
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis

Stefan Judis | Sciencx (2025-01-19T23:00:00+00:00) Template Literal Types for validating files names (#snippet). Retrieved from https://www.scien.cx/2025/01/19/template-literal-types-for-validating-files-names-snippet/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.