Open In App

TypeScript Capitalize<StringType> Template Literal Type

Last Updated : 25 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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-

  • Capitalize is the utility itself.
  • StringType is the type you want to capitalize. This is the input type that you want to capitalize. It can be a string literal type, a string union type, or any other string type.

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.

Javascript




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


Output:z59

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.

Javascript




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:z60



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads