Is it possible in TypeScript to change a string literal type into a number type?

Would it be feasible to develop a utility type Number<T> that can take a string literal type and convert it into a number? If conversion is not possible, should the utility return a never type?

type Five = Number<'5'> // `Five` is considered as the number 5

In anticipation of addressing questions regarding the purpose of this utility:

The reason for posing this question is my attempt to create an Add utility type for adding numbers.

type createArray<Len, Ele, Arr extends Ele[] = []> =  Arr['length'] extends Len ? Arr : createArray<Len, Ele, [Ele, ...Arr]>

type Add<A extends number, B extends number> = [...createArray<A, 1>, ...createArray<B, 1>]['length']

At present, the utility functions correctly with:

type Answer = Add<3,10> // The answer is 13

However, it currently only works with the number type. It would also be desirable for it to exclude the string type, allowing functionality like this: type Answer = Add<'3','10'>

Answer ā„–1

With the upcoming TypeScript 4.8 release, it will be possible to convert string literal types into other types such as number, bigint, or boolean. You can find more details in this PR.

By defining a utility type called ParseInt, we are able to "cast" a string literal to a number type.

type ParseInt<T> = T extends `${infer N extends number}` ? N : never

type T0 = ParseInt<"1">    // 1
type T1 = ParseInt<"100">  // 100
type T2 = ParseInt<"-13">  // -13
type T3 = ParseInt<"abc">  // never

Below are examples demonstrating conversions for other types:

type ParseBigint<T> = T extends `${infer N extends bigint}` ? N : never

type T4 = ParseBigint<"1">    // 1n
type T5 = ParseBigint<"100">  // 100n
type T6 = ParseBigint<"abc">  // never


type ParseBoolean<T> = T extends `${infer N extends boolean}` ? N : never

type T7 = ParseBoolean<"true">   // true
type T8 = ParseBoolean<"false">  // false
type T9 = ParseBoolean<"abc">    // never

Take a look at it in action on the TypeScript playground here.

Answer ā„–2

Turning an arbitrary string literal type into a numeric literal type (referred to as StringToNumber<T>) is not possible. There was a request made at microsoft/TypeScript#47141 for this feature, but it was declined by the TypeScript team. They are not inclined to support it. Another open issue at microsoft/TypeScript#26382 requests support for performing arbitrary mathematics on literal types, including StringToNumber<T>; however, the outcome is uncertain.


If your requirement is limited to non-negative whole numbers below 1000, you can implement this functionality yourself using tuple manipulation and recursion, similar to how Add works:

type StringToNumber<T extends string, A extends any[] = []> =
  T extends keyof [0, ...A] ? A['length'] : StringToNumber<T, [0, ...A]>

You can test it with examples like:

type Thirteen = StringToNumber<"13">;
// type Thirteen = 13

However, keep in mind that this method has limitations similar to Add, and providing unexpected inputs may lead to compiler performance issues or errors.

The input strings should be restricted to valid numeric values:

type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "";
type NonZero = Exclude<Digit, "0" | "">
type LessThanAThousand = "0" | `${NonZero}${Digit}${Digit}`

type StringToNumber<T extends LessThanAThousand, A extends any[] = []> =
  T extends LessThanAThousand ? T extends keyof [0, ...A] ?
  A['length'] : StringToNumber<T, [0, ...A]> : never;

type Oops = StringToNumber<"0.4"> // error
// ----------------------> ~~~~~
// Type '"0.4"' does not satisfy the constraint 'LessThanAThousand'.(2344)

This approach may work, but caution is advised unless there is a strong justification for its use. The TypeScript team does not consider the utility of Add type worth supporting, which could explain why the request for StringToNumber<T> was declined.

Playground link to code

Answer ā„–3

To manually create a custom Map, follow these steps:

type MapStrNum = {
  "apple": 1;
  "banana": 2;
};

Next, implement this:

type One = MapNumStr['apple'] // One will equal 1

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

The debate between using "this" versus "classname" to access static elements in

When working with TypeScript, I've observed that there are multiple valid approaches for accessing a static class member. class MyClass { private static readonly FOO: string = "foo"; public DoSomething(): void { console.log(MyClass.FOO);} pu ...

Harnessing the power of the map function in TypeScript

Here is a collection of objects: let pages = [{'Home': ['example 1', 'example 2', 'example 3']}, {'Services': ['example 1', 'example 2', 'example 3']}, {'Technologies&apos ...

Connecting HTML to an AngularFirestore collection using snapshotChanges

In my mobile app, I am using AngularFirestore2v5/rxjs to connect a hybrid Ionicv3/Angularv4 app to a Firestore collection. While binding UI with AngularFirestore.valueChanges works fine, switching to snapshotChanges for retrieving the id is causing some is ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

Utilizing Protractor, TypeScript, and Jasmine for Automated Testing

Just landed a new job at a company that uses protractor, jasmine, and Type Script for automation testing. While I have experience with selenium and Java, I'm unfamiliar with protractor. Can someone guide me on how to start protractor testing? Is there ...

Using Angular 12 to seamlessly import JSON files into TypeScript

My project contains a JSON file located at src/assets/version.json with the following content: {"VERSION":"1.0.0"} I have imported this file into a TypeScript file (e.g., *.ts) as shown below: import * as VersionInfo from 'src/ass ...

Encountering issues with package resolution in VS Code while setting up a monorepo with yarn workspaces, Vite, React, and

I recently set up a monorepo using yarn@3 workspaces. Here is the structure of my root package.json: { "name": "hello-yarn-workspaces", "packageManager": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Expanding the base class and incorporating a new interface

(Here is an example written using Typescript, but it applies to other cases as well) class IMyInterface { doC:(any) => any; } class Common { commonProperty:any; doA() { } doB() { } } class ClassA extends Common {} class Clas ...

Innovative techniques for class manipulation

Is there a way to implement type checking when extending a class with dynamic methods? For example, if you want to add methods to a class based on options provided to the constructor. This is a common scenario in plain JavaScript. const defaults = { dyn ...

Conditional types can be used as type guards

I have this simplified code snippet: export type CustomType<T> = T extends Array<unknown> ? {data: T} : T; function checkAndCast<T extends Array<unknown>>(value: CustomType<T>): value is {data: T} { return "data" ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

atom-typescript - What could be causing the unrecognized Typescript configuration options?

I'm puzzled as to why I am encountering the errors depicted in the screenshot below. Atom is indicating that my tsconfig.json file has 'project file contains invalid options' for allowJs, buildOnSave, and compileOnSave. However, according ...

Mapping nested values from a Typescript object to properties of a JSON object

Within the scope of a current project I am involved in, we have opted for utilizing the Angular toolset identified as formly to dynamically generate our forms. The present configuration of the form is hardcoded into a Typescript object denoted as mockForm ...

Error: The 'Window' object is not defined. The use of Client in NextJS13 is not

I've been attempting to integrate NextJS 13 with react-leaflet, but I keep encountering the error "window is not defined" when running my component. I attempted using the "use client" declaration at the beginning of the file and adding a check for "ty ...

Declare the push method within the Countly.q array in a TypeScript declaration file

Is there a way to declare Countly push add_event method in the following manner? Countly.q.push(['add_event',{ "key":"action_open_web", }]); I attempted to do this inside a declaration file (.d.ts) but it did not work. Here ...

Encountering a tslint issue: "Parsing error: Expression expected"

Could someone provide some insight on this issue? Iā€™m encountering an error message that says Failed to compile. Parsing error: Expression expected with this specific line of code - isLogViewVisible: dashboard?.logView !== null where the variable isLog ...

What is the best method for implementing Datepicker translations in Angular?

I am looking to incorporate the DatePicker component in Angular, enabling users to select a date that can be translated based on their browser's settings. Any suggestions on how to achieve this? <mat-form-field appearance="fill"> ...

Steps for utilizing field labels to transmit values in Protractor

Could someone offer guidance on how to send values using field labels? I understand that it's generally not recommended to use labels for sending values since they can change, but in my case, the labels remain constant. I have attached screenshots of ...

Creating asynchronous JavaScript constructors using a static method called "create" presents challenges when dealing with TypeScript types

I've been diving into the world of asynchronous constructors and have successfully implemented them in JavaScript. However, I'm facing a challenge with TypeScript types. Here's how it should ideally work: const a: AnyClass = await AnyClass. ...

Tips for organizing HTML logic in a separate document

I am faced with the task of displaying a list in HTML based on specific conditions: <!-- Display list if there are more than 5 results --> <div list.numberOfResults > 10"> <b>Name: </b>{{list.name}} <b>ID ...