Hone logo
Hone
Problems

Uppercase Type in TypeScript

This challenge asks you to create a TypeScript utility type that transforms a string literal type into its uppercase equivalent. This is useful for enforcing consistent casing in string literals, such as API keys, CSS class names, or configuration options where uppercase is a standard.

Problem Description

You need to implement a TypeScript branded type Uppercase<T> that takes a generic type parameter T. This T is expected to be a string literal type. Your Uppercase<T> type should return a new string literal type where all characters of the input T are converted to their uppercase equivalents.

Key Requirements:

  • The type must work with string literal types.
  • It should handle all alphabetic characters, converting them to uppercase.
  • Non-alphabetic characters (numbers, symbols, spaces) should remain unchanged.
  • The original type T should not be modified beyond casing.

Expected Behavior:

If T is "hello", Uppercase<T> should resolve to "HELLO". If T is "HelloWorld123!", Uppercase<T> should resolve to "HELLOWORLD123!".

Edge Cases to Consider:

  • Empty string literal.
  • String literals with only non-alphabetic characters.
  • String literals with mixed casing.

Examples

Example 1:

type Greeting = "hello";
type UppercaseGreeting = Uppercase<Greeting>;
// Expected type: "HELLO"

Explanation: The input string literal "hello" is converted to its uppercase form "HELLO".

Example 2:

type MixedString = "TypeScriptRocks!";
type UppercaseMixed = Uppercase<MixedString>;
// Expected type: "TYPESCRIPTROCKS!"

Explanation: The input string literal "TypeScriptRocks!" has its alphabetic characters converted to uppercase, while the exclamation mark remains unchanged.

Example 3:

type Empty = "";
type UppercaseEmpty = Uppercase<Empty>;
// Expected type: ""

Explanation: An empty string literal should result in an empty string literal.

Constraints

  • The solution must be a TypeScript utility type.
  • The input T will always be a string literal type or a union of string literal types.
  • The output type must also be a string literal type or a union of string literal types.

Notes

TypeScript 4.1 and later have built-in template literal types that can be used to achieve this. You should leverage these features to implement the Uppercase type. Think about how you can iterate over the characters of a string literal type and apply a transformation to each character.

Loading editor...
typescript