DEV Community

Cover image for How to convert the first letter of a string literal type into an uppercase format or capitalize in TypeScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to convert the first letter of a string literal type into an uppercase format or capitalize in TypeScript?

Originally posted here!

To convert the first letter of string literal type into an uppercase format or capitalize, you can use the built-in Capitalize type that comes with TypeScript.

TL;DR

// string literal type
type Greeting = "hello";

// convert first letter of
// string literal type
// into uppercase format or capitalize
type GreetingCapitalized = Capitalize<Greeting>; // Hello
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a string literal type like this,

// string literal type
type Greeting = "hello";
Enter fullscreen mode Exit fullscreen mode

Now to capitalize the string literal type let's use the Capitalize built-in type and pass the Greeting type into it using the angled bracket (<>) syntax.

It can be done like this,

// string literal type
type Greeting = "hello";

// convert first letter of
// string literal type
// into uppercase format or capitalize
type GreetingCapitalized = Capitalize<Greeting>; // Hello
Enter fullscreen mode Exit fullscreen mode

Now if you hover over the GreetingCapitalized type you can see that the hello string literal type is now capitalized. Yay 🥳.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)