Create Dynamically Typed Strings Using Template Literal Types

InstructorKamran Ahmed

Share this video with your friends

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.