One inventive method for tagging various strings within Typescript Template Literals

As TypeScript 4.1 was released, many developers have been exploring ways to strictly type strings with predetermined patterns. I recently found a good solution for date strings, but now I'm tackling the challenge of Hex color codes.

The simple approach of defining HEX = 0 | 1 | ... | "E" | "F" and then declaring

type HEX_CODE = `#${HEX}${HEX}${HEX}${HEX}${HEX}${HEX}`;

creates a type that is too complex due to the union of too many types.

So, I thought about requiring the "#" symbol in front of the hex code like this:

type HEX_CODE = `#${arbitraryString}`;

However, I'm struggling to implement this. If anyone knows how to make it work or can suggest another compromise on the type, please share your insights.

Answer №2

UPDATE 28 August 2022

For the latest information, check out this answer and the updated article

Here is a solution:

UPDATE

If the string length is not equal to 6, it will now throw an error

type HexNumber = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
type HexString = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
type StringNumber<T extends number> = `${T}`
type HEX = HexNumber | StringNumber<HexNumber> | HexString;

// More code snippets follow...

Playground

This solution should only be used for function arguments in real-world scenarios

const hex = <T extends string, U extends {
    'valid': 'valid',
    'invalid': 'invalid',
}[Check<T> extends string[] ? Mapper<Check<T>> extends T ? 'valid' : never : 'invalid']>(value: T, ...rest: U extends 'valid' ? [] : [never]) => value

const result = hex('aaaaaf') // ok
const result2 = hex('aaaaaZ') // error

Playground 2

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

When buttons are clicked within Angular Material's Card component, it automatically triggers the click event of the card itself

One of the challenges I'm facing is having a mat-card within a component template: <mat-card *ngFor="let p of products" (click)="viewProduct(p)"> <mat-card-actions> <button mat-stroked-button (click)="addProductToCart(p)"&g ...

Can you merge two TypeScript objects with identical keys but different values?

These TypeScript objects have identical keys but different properties. My goal is to merge the properties from one object onto the other. interface Stat<T, V> { name: string; description: string; formatValue: (params: { value: V; item: T }) =&g ...

Discovering how to display the hidden messages section in the absence of any ongoing chats with the help of angular2

I currently have 2 tabs set up on my page. The active messages tab is functioning perfectly without any issues. However, I am encountering an error with the closed messages tab. If there are no messages in this tab, the system displays an error message w ...

"Here's a comprehensive guide on how to connect dynamic data with angular-tree-grid components

ERROR TypeError: Cannot read property 'map' of undefined Can anyone help with binding dynamic data? I'm currently using angular-tree-grid but struggling to bind dynamic data. <html> <db-angular-tree-grid (expand)= ...

Is it possible to iterate over an enum using Object.entries<T>(Enum).map() in TypeScript, or does it only function with string-based enums?

Currently, I am in the process of developing a react form that requires users to select options related to a job. These options are represented by enums, with some being string-based and others number-based. For instance, here is an example of a string-ba ...

Error in Vuetify 3.1.2 with Vue 3 and TypeScript: Unable to assign type 'boolean' to type 'never'

I am currently building a project using Vue 3 (version 3.2.45), Typescript (version 4.9.4), and Vuetify (version 3.1.2). When working with Vuetify components, I often encounter situations where I need to pass specific props for styling, positioning, or ma ...

Utilize multiple validators.patterns within a single value for enhanced data validation

I need to implement two different patterns for the formControlName='value' based on the type selected. If type is 'A', I want to use the valuePattern, and if type is 'B', I want to use the uname pattern. This is my HTML code: ...

Error encountered with object.map() function - what fundamental concept am I missing?

Could someone lend me a fresh set of eyes on this... The React Component is fetching data from MariaDB using a useEffect() hook. The data is retrieved successfully without any errors, and the console.log shows the correct data (refer to the image below). ...

The 'ref' attribute is not found within the 'IntrinsicAttributes' type

I'm currently working on a TypeScript project using React. Although the code is functional, I keep encountering compiler errors with my ref. Here's an example of the code: Firstly, there's a higher-order component that handles errors: expor ...

I am encountering a TypeScript error with URLSearchParams. The object cannot be successfully converted to a string using the toString() method

During the development of my react app with postgres, express, node, and typescript, I ran into an issue while working on the backend code. The problem arises when trying to utilize URLSearchParams. index.js import express from 'express'; import ...

Develop a variety of Jabber client echo bots

Hello Stackoverflow Community, I've been trying different approaches to resolve my issue, but I keep ending up with stack overflow errors. Programming Language: Typescript Main Objective: To create multiple instances of the Client Class that can be ...

Sending returned values from a promise to the calling function in Angular

I have a created a promise to retrieve values from a service and then assign them to variables trans and confidence, which should be used as transcript and conf in the save_data function. How can I return these values to the calling function and ensure tha ...

Angular2 app fails to update after emitting an event

I need help with a child component responsible for updating phone numbers on a webpage. The goal is for the application to automatically display the changed phone number once the user hits the 'save' button. Here's a visual of how the appli ...

Display or conceal elements within a Component with the help of a Service

After developing a custom Tabs component, I have implemented it in the following way (StackBlitz example): <tabs> <tab title="Tab 1"> <div toolbar> <message><span>Message 1: </span></message> &l ...

I want to know the best way to send latitude and longitude coordinates from an external source in order to generate a

Looking for advice on customizing a working code that uses leaflet angular to place markers with predefined latitudes and longitudes. I want to be able to customize this by passing latitudes and longitudes when the addmarker button is pr ...

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

A tip for transferring the value of a binding variable to a method within the template when the button is clicked

I am currently exploring the concept of binding between parent and child components using @Input, @Output, and EventEmitter decorators. This is demonstrated in the HTML snippet below: <h1 appItemDetails [item]="currentItem">{{currentItem}}& ...

Creating an object efficiently by defining a pattern

As a newcomer to Typescript (and Javascript), I've been experimenting with classes. My goal is to create an object that can be filled with similar entries while maintaining type safety in a concise manner. Here is the code snippet I came up with: le ...

Node.js - Creating seamless integration between Sequelize model JS and controller TS

Having trouble making my User.js model recognized inside my UserController.ts with sequelize in TypeScript. Edit: Unable to change the file extensions for these files. In the await User.findAll() part, an error occurs when running on the server, stating ...

Input the variant number TypeScript as the key value pair

I'm struggling to input an abi key "5777" in Typescript. When I receive a network ID and try to set it in the networks key, the linter displays an error. My issue is that I need to specify "networkId" and it's not always a fixed value like "5777 ...