Open In App

TypeScript Capitalize<StringType> Template Literal 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-



Approach: Let us see how we can use the Capitalize<StringType> step-by-step:

Step 1: Start by defining a string type that you want to capitalize. This can be a string literal or a string type alias:



type originalString = "hello, world";

Step 2: Apply the Capitalize<StringType> template literal type to the defined string type. This will create a new type with the string type’s characters capitalized:

type CapitalizedString = Capitalize<originalString>;

Step 3: You can now use the CapitalizedString type to declare variables, function parameters, or any other TypeScript type annotations:

const greeting: CapitalizedString = "Hello, World";

Step 4: The greeting variable now has the type CapitalizedString, ensuring that it contains a string with the first letter capitalized and the rest in lowercase.

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:


Article Tags :