Open In App

TypeScript Uppercase<StringType> Utility Type

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

In this article, we are going to learn about Uppercase<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 Uppercase<StringType> Template Literal Type which is a built-in utility type that helps with string manipulation. It helps to convert all the characters in a given StringType to uppercase.

Syntax:

type UppercaseString = Uppercase<StringType>; 

Where

  • Uppercase is the utility itself.
  • StringType is the input type that you want to convert to uppercase. 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 Uppercase<StringType> step-by-step:

Step 1: Start by defining a string type variable or type alias that you want to convert to uppercase:

type MyString = "hello world"; 

Step 2: Apply the Uppercase<StringType> template literal type to the string type variable or alias to convert it to uppercase:

type UppercaseString = Uppercase<MyString>; 

Step 3: You can now use the converted uppercase string type in your code, assign it to variables, or use it in type annotations:

const result:UppercaseString="HELLO WORLD"
console.log(result)

Step 4: Now, we can validate our string using this.

Example 1: In this example, MyString is defined as “hello world,” and UppercaseString is defined as Uppercase<MyString>. The result is that UppercaseString will be of type “HELLO WORLD”, with all characters converted to uppercase.

Javascript




type MyString = "hello world";
type UppercaseString = Uppercase<MyString>;
const result: UppercaseString = "HELLO WORLD"
console.log(result)


Output: z52

Example 2: In this example, we have a Colors type that represents different color names in lowercase. We then use the Uppercase template literal type to create UppercaseColors, ensuring that any value assigned to it must be in uppercase. The primaryColor assignment is valid because “RED” is correctly in uppercase, matching the UppercaseColors type. However, the invalidColor assignment is not valid because “blue” is not in uppercase as per the type constraint.

Javascript




type Colors = "red" | "green" | "blue";
type UppercaseColors = Uppercase<Colors>;
const primaryColor: UppercaseColors = "RED"; // Valid
console.log(primaryColor)
const invalidColor: UppercaseColors = "blue"; // Invalid


Output:z53



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads