Open In App

TypeScript Lowercase <StringType> Utility Type

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

In this article, we are going to learn about Lowercase<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 Lowercase<StringType> Template Literal Type, a built-in utility type that helps with string manipulation. It helps to convert each character in the string to the lowercase version.

Syntax:

type LowercaeString = Lowercase<Stringtype>

Where

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

Example 1: This example shows a simple example of using Lowercase<StringType> Template Literal. ‘MyString’ is defined as “HelloWorld” and LowercaseString is defined as ‘Lowercase<MyString>. The result is that ‘LowercaseString’ will be of type “helloworld”, with all characters in lowercase.

Javascript




type MyString = "HelloWorld";
type LowercaseString = Lowercase<MyString>;
const result: LowercaseString = "helloworld";
console.log(result);


Output:

z45

Example 2: In this example, we have a ‘Course’ type that can only take on three specific string values: “Java”, “python”, and “React”. We then use the ‘Lowercase’ template literal type to create ‘LowercaseCourse’ which ensures that any value assigned to it must be lowercase. React will give an error since it is not in lower. Others are in lowercase so they will not cause errors.

Javascript




type Course = "Java" | "Python" | "React";
type LowercaseCourse = Lowercase<Course>;
const myCourse: LowercaseCourse = "java"; // Valid
const myCourse2: LowercaseCourse = "python"; // Valid
  
// const myCourse3:LowercaseCourse = "React"; // Invalid
console.log(myCourse);
console.log(myCourse2);


Output:

z46

Conclusion: In this article, we have seen what is Lowercase<StringType> and its syntax. Since it can be used to convert each character in the string to the lowercase version. By using the Lowercase<StringType>, you can ensure that all the values are in lowercase or not. It helps in Validation.

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads