How to type fixed string value combinations with template literal types
Written by Stefan Judis
- 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 yearstypereleaseYear = '2022' | '2023' | '2024';// define release monthstypereleasteMonth = '03' | '07' | '11';// combine the two types in a template literal typetypeversionNumber = `${releasteMonth }.${releaseYear }`;constType '"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"'?: version versionNumber = '04.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 15 days ago.
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 15 days ago.