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!

Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 1 days ago.

Related Topics

Related Articles

About the author

Stefan standing in the park in front of a green background

Frontend nerd with over ten years of experience, "Today I Learned" blogger, conference speaker, Tiny helpers maintainer, and DevRel at Checkly.