Open In App

TypeScript Capitalize <StringType> Utility Type

In this article, we are going to learn about Capitalize<StringType> Template Literal Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. One of the features of Typescript is Capitalize<StringType> Template Literal Type which is a built-in utility type that helps with string manipulation. It helps to capitalize the first letter of each word in a given StringType.

Syntax:



type CapitalizedString = Capitalize<StringType>; 

Where

Example 1: In this example, MyString is defined as “hello world,” and CapitalizedString is defined as Capitalize<MyString>. The result is that CapitalizedString will be of type “Hello”, with the first letter capitalized.






type MyString = "hello";
type CapitalizedString = Capitalize<MyString>;
const result: CapitalizedString = "Hello";
console.log(result);

Output:

Example 2: In this example, we have a DaysOfTheWeek type that represents the names of the days of the week in lowercase. We then use the Capitalize template literal type to create CapitalizedDays, ensuring that any value assigned to it must have the first letter of each word capitalized.




type DaysOfTheWeek = "sunday" | "monday" | "tuesday"
   | "wednesday" | "thursday" | "friday" | "saturday";
  
type CapitalizedDays = Capitalize<DaysOfTheWeek>;
  
const today: CapitalizedDays = "Saturday"; // valid 
  
console.log(today);
// const invalidDay: CapitalizedDays = "tuesday"; // invalid

Output:

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

Conclusion: In this article, we have seen what is Capitalize<StringType> and its syntax. Since it can be used to capitalize the first letter of each word in a given StringType.


Article Tags :