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
type ImageExtension = `png` | `jp${`e` | ``}g` | `webp`;
type ImageFileName = `${Lowercase<string>}.${ImageExtension}`;
ย 
const goodName1: ImageFileName = 'doggy1.jpeg';
const goodName2: ImageFileName = 'doggy2.jpg';
const badName: ImageFileName = 'KittyCat.webp';
Type '"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`'.

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.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles