Open In App

What are template literal types in Typescript ?

Template literal types in typescript are based on string literal types and may be expanded into many strings using unions. They have the same syntax as JavaScript’s template literal strings, but they’re utilized in type locations. When used with tangible literal types, a template literal concatenates the contents to create a new string literal type.

Syntax: The following is the syntax of creating template literals:



${...}

Note: ` ` is used instead of “” while creating template literals. 

Example 1: Concatenating string literals with strings.



In the below code we create a string literal and it is further concatenated with another string in “ ticks, using the ${} syntax. A new type is formed. 




type coding = "coding";
type sentence = `i like ${coding}`;
  
let sentence1: sentence = "i like coding";
console.log(sentence1);

Output:

i like coding 

Example 2: A new type can be formed by using union to concatenate string literals type with other string using template literal syntax. The type is the collection of all potential string literals that each union member might represent.




type Headings = "h1" | "h2" | "h3" | "h4" | "h5";
type Paragraphs = "p";
  
type AllLocaleIDs = `${Headings | Paragraphs}_tag`;

Output:

type AllLocaleIDs = “h1_tag” | “h2_tag” | “h3_tag” | “h4_tag” | “h5_tag” | “p_tag”

Example 3: Cross multiplication of unions. In this example, we cross multiply two unions. By using template literals we cross multiply unions. 




type A = 'a1'|'a2'|'a3';
type B = 'b1'|'b2'|'b3';
  
type concat = `${A}_${B}`;

Output:

type concat = “a1_b1” | “a1_b2” | “a1_b3” | “a2_b1” | “a2_b2” | “a2_b3” | “a3_b1” | “a3_b2” | “a3_b3”

Reference: https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html


Article Tags :