Monday, June 20, 2022

How Template Literal Types Work in TypeScript

Template Literals are common in JavaScript: they let us easily combine variables and strings in JavaScript. TypeScript also introduces the concept of Template Literal Types, where we can enforce types on the inputs for Template literals. That gives us controls to ensure that text is in a certain format. Let's look at how they work.

Template Literal Types in TypeScript

A perfect example of when a template literal type might be useful is for creating IDs of certain formats. For example, let's say we have an ID that starts with 'ga-' or 'ua-', followed by a string or number. We can define a new type using type literals for that like so:



from DZone.com Feed https://ift.tt/tSHKyjM

No comments:

Post a Comment