TypeScript: Type safe date strings. Recently, Template literal types give developers the opportunity not only to declare that a certain variable should be of type string. Behold; Type safety date strings!
Recently, TypeScript 4.1 was released, and with it template literal types.
Template literal types give developers the opportunity not only to declare that a certain variable should be of type string, but it further allows developer to declare format of the string as well.
If you’re asking yourself the above question, you’re in luck! This article is meant to showcase one such example! Behold; Type Safe Date Strings!
So let’s go ahead and take a look at a possible implementation of how this can be done.
Let’s assume first that our application has two base date strings, DateYMString and DateYMDString. These are respectively on the format YYYY-MM
, and YYYY-MM-DD
. We assume that valid years are any years between 1900 and 2099. While this constraint might seem a bit arbitrary at the moment, I will explain after the example why these bounds are indeed necessary.
We are going to construct our types DateYMString
and DateYMDString
based on smaller, modular template literal types. Let’s first consider the types we want to end up with:
export type DateYMString = `${YYYY}-${MM}`;
export type DateYMDString = `${DateYMString}-${DD}`;
While you might not have seen this kind of TypeScript syntax before, the example should be simple enough. We’ve declared them as consisting of our yet to be declared YYYY
(years), MM
(months) and DD
(days) template literal types.
TypeScript extends JavaScript by adding Types. There are many great reasons to switch to TypeScript. Especially if your team uses JavaScript. There are some reasons to not use TypeScript as there are with any language or framework.
TypeScript Tutorial For JavaScript Developers - TypeScript Basics. I will show you guys 4 example of JavaScript code, and how to convert it to TypeScript. This is a typescript beginners tutorial.
Multi-paradigm, Functional, Generic, Imperative, Object-Oriented. In this article, I have shared the essential information about TypeScript programming language. This article contains a basic overview, brief history, features and applications of TypeScript. TypeScript is getting more popular in Full-stack development. In terms of popularity, in the last two years TypeScript pulled ahead of Ruby, Shell, and C.
In this article, I will discuss my journey from being an anti-TypeScript developer to a developer who now couldn’t think of going back to the plain JavaScript world. Let's see How an Anti-TypeScript “JavaScript Developer” Like Me Became a TypeScript Fan.
Functional Programming: Exploring the Functor type class and its use cases