Published at
Updated at
Reading time
1min

Sometimes, I'm surprised about how smart TypeScript is. Let's assume you want to type your app's release version numbers. The format is [releaseMonth]-[releaseYear]. There won't be a new version every month or year.

How hard is it to define a type for this? It's not hard at all.

js
// define release years
type releaseYear = '2022' | '2023' | '2024';
// define release months
type releasteMonth = '03' | '07' | '11';
// combine the two types in a template literal type
type versionNumber = `${releasteMonth}.${releaseYear}`;
 
const version: versionNumber = '04.2022';
Type '"04.2022"' is not assignable to type '"03.2022" | "03.2023" | "03.2024" | "07.2022" | "07.2023" | "07.2024" | "11.2022" | "11.2023" | "11.2024"'. Did you mean '"03.2022"'?2820Type '"04.2022"' is not assignable to type '"03.2022" | "03.2023" | "03.2024" | "07.2022" | "07.2023" | "07.2024" | "11.2022" | "11.2023" | "11.2024"'. Did you mean '"03.2022"'?

For these situations, TypeScript defines Template Literal Types based on good old template strings. Sweet!

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