Create Dynamically Typed Strings Using Template Literal Types

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet

Template literal types allow you to create dynamically typed strings. In this lesson, we learn how to further solidify your typings using the template literal types. They have the same syntax as template literal strings in JavaScript, but are used in type positions. When used with concrete literal types, a template literal produces a new string literal type by concatenating the contents.

type World = "world";

// Greeting type can now only be assigned hello world
type Greeting = `hello ${World}`;

When a union is used in the interpolated position, the type is the set of every possible string literal that could be represented by each union member:

type EmailLocaleIDs = "welcome_email" | "email_heading";
type FooterLocaleIDs = "footer_title" | "footer_sendoff";

// Possible values for this type: "welcome_email_id" | "email_heading_id" | "footer_title_id" | "footer_sendoff_id"
type AllLocaleIDs = `${EmailLocaleIDs | FooterLocaleIDs}_id`;

You can also read more about them in the TypeScript documentation.

Kamran Ahmed: [0:00] Here we have a handler function which is accepting a parameter called eventType which is of type string, and it is printing to the console 'handling ${eventType}'. Here we're calling this handler function with a bunch of events onClick, onKeydown and onKeyup. We can also have handler('onEnter') and so on.

[0:20] The problem with this eventType string is that we are not enforcing the eventType here. Always have the eventType as on something, so onescape and so on. Right now, we are not enforcing that, and we can call handler('clicker'), handler('escapekey') and so on, and it is not failing right now because we don't enforce the eventType properly here.

[0:45] Because we want to enforce the prefix of on in front of all the strings, we can replace the string with on, and then string here. Now, if you run this, you will see that clicker and escapekey are failing because they don't have the prefix of on here, but if I add on in the beginning, this is also passing now.

[1:04] We can also enforce specific keys here inside the template literal types, so I can replace this string with let's say click and keydown. Now you see here the onClick and onKeydown are passing, but the rest of the events are failing, and if I replace this again with the type string here, all these on events are passing.