Leverage Typescript to convert string literal types to uppercase

type x = 'first' | 'second'

I am looking to create a type y that is similar to this:

type y = 'FIRST' | 'SECOND'

Here is what I attempted:

type x = 'first' | 'second'
type y = {[key in x]: key['toUpperCase']}

Unfortunately, this did not achieve the desired outcome.

Appreciate you taking the time to read :)

Answer №1

With the advent of Template Literal Types, you can now achieve the following:

type A = 'one' | 'two'
type B = Uppercase<A>

let b: B = 'one' // Type '"one"' is not assignable to type '"ONE" | "TWO"'.

Try it on TS Playground

In addition to using Uppercase<StringType>, there are other useful helper types available as well:

  • Lowercase
  • Capitalize
  • Uncapitalize

You can incorporate them into Template Literal Types like so:

type Fruit = 'Apple' | 'Banana'
type FruitField = `fr_${Uncapitalize<Fruit>}`

const fruit: Record<FruitField, boolean> = {
    'fr_apple': true,
    'fr_banana': false,
    'fr_Apple': true, // error
    'fr_peach': false // error
}

See it in action on TS Playground

Answer №2

Click on this link to access TS Playground

Here is the code snippet:

type A = 'one' | 'two'
type B = Uppercase<A>

let b: B = 'one' // This line will throw an error

On a side note, I find it confusing why a more complex method was used in the previous response to convey the same message.

UPDATE: Derek Nguyen (top answer) has revised their solution with a simpler approach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the specific types of subclasses derived from an abstract generic class in Typescript

There is a Base generic class: abstract class BaseClass<T> { abstract itemArray: Array<T>; static getName(): string { throw new Error(`BaseClass - 'getName' was not overridden!`); } internalLogic() {} } and its inherito ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

What could potentially be the reason behind the incapability of the next.js Image component to transform the svg into a

Unique Context I recently developed a minimalist Hero + Navbar using Next.js. The site utilizes the powerful next.js Image component to display images. Surprisingly, all three images on the website, which are in .webp format, load instantly with a size of ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database: $scope.submit = function(){ var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name; console.log(url); $ht ...

Can you provide a brief explanation for this bubble sort JavaScript code?

Can someone please explain to me what the line j<len-i is doing in this bubble sort code? I believe removing -i from that line will still make the program work properly, var arr=[3,5,4,7,8,9,30,0,-1]; function bubble_Sort(arr){ var len = arr.length, ...

Narrow down product selection by multiple categories

I'm currently in the process of working with Express and MongoDB, where I have data items structured like the following: { "_id": { "$oid": "63107332e573393f34cb4fc6" }, "title": "Eiffel tower&quo ...

Utilizing Node.js for Gmail API: Extracting Inline/Embedded Images

When working with email data, one approach is to use the gmail.users.messages.get() method. After fetching the email data, there are two functions used to handle the payload. function getBody(message) { var encodedBody = ''; try{ i ...

Get rid of the .php extension in the URL completely

Lately, I've been experimenting a lot with the .php extension. I successfully used mod_rewrite (via .htaccess) to redirect from www.example.com/example.php to www.exmaple.com/example. Everything is running smoothly. However, I noticed that even though ...

Revamping the Look: Refreshing Background of Div

I'm attempting to change the background image of the body element on a webpage when I hover over links with data-* attributes. It's working perfectly, but I can't seem to figure out how to create a smooth fade between the images when a link ...

Can components be SSGed individually rather than entire pages?

I am currently working with Next.js and I am wondering if there is a way to statically generate and display the database values in the header and footer components used across all pages. While getStaticProps can generate pages statically, it doesn't ...

Guide: Ensuring the validity of an object retrieved from a database with Nest.js class-validator

When activating a user, I need to ensure that certain optional data in the database is not empty by using class-validator dto. So far, my controller level validations for body, query, and all other aspects have been successful. The DTO file contains vali ...

Disable dates that are more than 7 days from the current date using Material UI's Date

How can I restrict users from selecting dates more than 7 days after their initial selection? In the example image provided, the date of January 30th should be disabled for selection. https://i.stack.imgur.com/iTem4.png Below is the code snippet: const ...

Google Analytics in Next.js Missing Page Title Configuration

I recently set up Google Analytics on my Next.js website, but I'm encountering a strange issue where the analytics are not detecting my webpages and showing as (not set). Everything else seems to be functioning properly. I've double-checked that ...

Utilize the identical function value within a Vue template

In my template, I am encountering a recurring situation where I need to retrieve a value from a function. This function takes parameters from the template (such as the index of a v-for loop) and returns a result that is then displayed on the template. The ...

Encountering a TypeScript type error when returning a promise from a function

I currently have a scenario in which there is a function that checks if user whitelisting is required. If not, it calls the allowUserToLogin function. If yes, it then checks if a specific user is whitelisted. If the user is not whitelisted, an error is thr ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

The TypeScript compiler generates a blank JavaScript file within the WebStorm IDE

My introduction to TypeScript was an interesting experience. I decided to convert a simple JavaScript application, consisting of two files, into TypeScript. The first file, accounts.ts, contains the main code, while the second one, fiat.ts, is a support f ...

React Typescript: The specified argument type cannot be assigned to the parameter type

Creating a Check Box Button React component has resulted in an error related to setRSelected(1) and setRSelected(2)... const [cSelected, setCSelected] = useState([]); const [rSelected, setRSelected] = useState(); const onCheckboxBtnClick = (selected ...