TypeScript definition for string representations of a combined type of numbers

I am exploring ways to create a TypeScript type that restricts values to specific string representations of numbers. Let's dive into the details:

Imagine having a union numeric type defined like this:

const ONE = 1;
const TWO = 2;

type ALLOWED_NUMBER = typeof ONE | typeof TWO;

Now, I want to come up with a string type that only allows the stringified versions of these numbers. Here is what I aim to achieve:

type ALLOWED_NUMBER_STRING = /* seeking a solution for this :) */

const numericStringA: ALLOWED_NUMBER_STRING = '1';    // no error
const numericStringB: ALLOWED_NUMBER_STRING = '3';    // error
const numericStringC: ALLOWED_NUMBER_STRING = 'foo';  // error

While I could manually define this type, my goal is to find an efficient way to avoid redundancy!

Answer №1

If you're searching for information on template literal types, look no further:

Check out this TS Playground example

const ONE = 1;
const TWO = 2;

type ALLOWED_NUMBER = typeof ONE | typeof TWO;
type ALLOWED_NUMBER_STRING = `${ALLOWED_NUMBER}`;

const numericStringA: ALLOWED_NUMBER_STRING = '1';

const numericStringB: ALLOWED_NUMBER_STRING = '3'; /*
      ^^^^^^^^^^^^^^
Type '"3"' is not assignable to type '"1" | "2"'.(2322) */

const numericStringC: ALLOWED_NUMBER_STRING = 'foo'; /*
      ^^^^^^^^^^^^^^
Type '"foo"' is not assignable to type '"1" | "2"'.(2322) */

To streamline a collection of numbers, consider optimizing with this method:

View the updated approach in the TS Playground demonstration

const allowedNumbers = [1, 2, 3] as const;
type AllowedNumber = typeof allowedNumbers[number]; // 1 | 2 | 3
type AllowedNumberStr = `${AllowedNumber}`; // "1" | "2" | "3"

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

Is React Typescript compatible with Internet Explorer 11?

As I have multiple React applications functioning in Internet Explorer 11 (with polyfills), my intention is to incorporate TypeScript into my upcoming projects. Following the same technologies and concepts from my previous apps, I built my first one using ...

Attempting to execute a post request followed by a get request

I need assistance optimizing my code. What I am trying to achieve is to create a user (partner) and upon completion of the post request, fetch all partners from an API. This includes the newly created partner so that I can access their ID to use in subsequ ...

Filtering nested arrays in Javascript involves iterating through each nested

I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code: var teams = [ { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name ...

Utilize Ngrx to keep an eye on specific items within the store

If we consider an interface called INotification: export interface INotification { id: number; DateReceived: number; Title: string; Message: string; Tipology: string; isRead: number; } and a reducer system. In the component, it&ap ...

Refactor JavaScript code with closures into a TypeScript class

Looking to convert the following JavaScript code into a TypeScript class. The greet2 function within the prototype is being used as an immediately invoked function. class Greeter { greeting: string; constructor(greeting: string) { this. ...

Lack of code completion in Nuxt options API when using typescript

After setting up Nuxtjs with typescript, I noticed that there are no code completions in the template and script as expected based on the title. Here is the code: <script lang="ts"> import Vue from 'vue'; import { FeaturedJobs } ...

Issue: Unable to locate API compiler-cli, function __NGTOOLS_PRIVATE_API_2

I am currently working on an Angular project and encountered the following errors, $ ng serve Your global Angular CLI version (8.3.21) is higher than your local version (7.0.7). The local Angular CLI version will be used. To disable this warning, us ...

Does it follow standard practice for Array.filter to have the capability to also perform mapping on an array of objects?

While experimenting with Array.filter, I made an interesting discovery. By forgetting to include an equality check, my array was unexpectedly mapped instead of filtered. Here is the code snippet that led to this result: const x = [{ name: 'user' ...

Converting Angular 4 RouterLink within InnerHTML to lowercase

I am facing an issue with a command I have, where I retrieve content from the server that includes HTML and links. The problem arises when displaying this data as the links do not work. Upon inspecting the page source, I noticed that "routerLink" is being ...

getting TypeScript configured with webpack

I am currently using Typescript to develop a back-end API utilizing graphql and express. To manage the project development and building process, I have implemented webpack. As part of my setup, I am employing raw-loader in order to load graphql schemas an ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Creating an NPM package using Visual Studio 2017: A Step-by-Step Guide

I enjoy developing and publishing NPM packages using Visual Studio 2017. My preferred method is using TypeScript to generate the JavaScript files. Which project template would be best suited for this particular project? ...

Is it possible to customize a VSCode extension to function exclusively with certain programming languages?

Lately, I added a new extension to my VSCode setup that has proven to be quite beneficial for my workflow. If you're interested, you can find this helpful extension at This Repository. It allows you to easily highlight the starting and ending syntax ...

Typescript: Creating a new type by filtering an interface for matching properties

Imagine you have an interface structured like this: interface endpoints { "/api/user/{id}": { get: operations["getUserGET"]; }; "/api/user/add": { put: operations["addUsingPUT"]; }; ... } Is it pos ...

Remove three rows from an array using Angular 7

I need assistance with a subtraction operation involving the first 3 rows of a table. TVA Collectée -TVA Déductible - Tva déductible/immo If the result is positive, I want to display it in the TVA à Payer box, and if it's negative, show it in th ...

Is ngOnDestroy executed within Angular services?

Is there a way to confirm if the ngOnDestroy method in my UserServiceService class is functioning properly? I want this service to continue running until the project starts and ends, with ngondestroy method executing once the application (website) is clo ...

React Typescript: exploring the power of dynamic types

Can dynamic typing be implemented? The JSON structure I am working with looks like this: { "fieldName": "Some text", "type": String, "inputType": "text" }, { "fieldName": "Some bool&q ...

Tips for avoiding the invalidation of a subquery within a Tanstack query

I am facing a dilemma with my queries: one for a single user and the other for a list of all users. The problem arises when I try to delete a user using a mutation. const { data: user, error, isLoading } = useQuery<User>( ['users', userId ...

Dealing with Placeholder Problems in Angular 2 Material when Using setValue

Encountering an issue with Angular2's material components when a component is updated via setValue. Check out the plnkr link below for more details... [unique PLNKR link] Observed that both the value and the placeholder are occupying the same space. ...

Simplify deeply nested JSON structures with TypeScript generics

After receiving the JSON data shown below, I have a specific model in mind for deserialization: {"results": {"data": { "id":"93cba9bd-2969-3214-b26f-7f42d20241a4", "first_name":"PSU", "last_name":"Bot", "profile": { "data":{"abou ...