How can TypeScript benefit from implementing more precise data types?

In TypeScript, is there a way to specify specific data types instead of just general number types? For instance, if I want a function to specifically return an integer type, is there a method to do so other than using:

function function_name (_params) : number {}
If not, what is the most effective approach to ensure that I get the desired types like integers or floats?

I attempted the following:

function function_name (_params) : int {}
but it was unsuccessful! One possibility could be to check at the time of returning a value if it is an integer by utilizing the modulo operator '%', but I was hoping for a more elegant solution, which led me to pose this question.

Answer №1

When it comes to JavaScript and TypeScript, the type system does not provide explicit support for various number types beyond number and bigint.

For dealing with integers in particular, TypeScript offers the number and bigint types to ensure compile-time checks that a number is indeed an integer, as illustrated in this example.

In certain scenarios where specific numbers are required, a literal union type can be utilized. For instance:

type PowerOfTwo = 1 | 2 | 4 | 8 | 16; // and so forth

An alternative method, applicable to other numeric sub-types as well, involves using a runtime check to verify that a number belongs to a given sub-type. By incorporating nominal typing along with an assertion function, TypeScript can acknowledge that such validation has been performed. For integers, this could involve utilizing Number.isInteger() for the runtime check:

type Int = number & { _brand: never };

function assertInt(n: number): asserts n is Int {
    if(!Number.isInteger(n)) {
        throw new Error(`${n} is not integer`);
    }
}

This assertion function can then be employed to create functions like integer division:

function divide(dividend: number, divisor: number): Int {
    const quotient = Math.floor(dividend / divisor);

    assertInt(quotient);
    return quotient;
}

const x = divide(5, 2); // x now has type Int

A wrapper function can also be crafted for inline checks:

function checkInt(n: number): Int {
    assertInt(n);
    return n;
}

Such a function proves useful when calling methods requiring parameters of type Int:

function multiply(multiplicand: Int, multiplier: Int): Int {
    const product = multiplicand * multiplier;

    assertInt(product);
    return product;
}

const y = multiply(checkInt(2), checkInt(4)); // y is of type Int

Playground link


TL;DR Numeric types have limited support in JavaScript and TypeScript. The distinction between different types mostly occurs at runtime, but nominal types and assertion functions can assist in convincing the TypeScript compiler about the true sub-type of a number.

Answer №2

If you've been looking for an Integer type in TypeScript without success, fear not! You can always create your own custom "types" with a little creativity. Here's a possible solution:

class IntegerMut {
  constructor(private value: number) {
    if (!globalThis.Number.isInteger(value)) throw new Error();
  }

  public set(value: number) {
    if (!globalThis.Number.isInteger(value)) throw new Error();

    this.value = value;
  }

  public get() {
    return this.value;
  }

  public add(value: number) {
    this.set(this.get() + value);
  }
}

class IntegerImm {
  constructor(private readonly value: number) {
    if (!globalThis.Number.isInteger(value)) throw new Error();
  }

  public get() {
    return this.value;
  }

  public add(value: number) {
    return new IntegerImm(this.get() + value);
  }
}

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 MongoDB connection in NextJS 14 is causing a delay in loading the page

Occasionally, when trying to open a page through the dashboard menu, nothing happens on the frontend. There's no loading screen or any indication that the page is being loaded. How can this problem be prevented so that the page loads as intended? This ...

Enhancing Web Service Calls with Angular 2 - The Power of Chaining

I am currently facing an issue where I need to make multiple web service calls in a sequence, but the problem is that the second call is being made before the .subscribe function of the first call executes. This is causing delays in setting the value of th ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Is it possible to import a module that was exported in Node.js using the SystemJS import method?

When working on a Node project, we typically import modules using the require keyword. Is it possible to import the same module in an Angular 2 project using import {} from '', even if the d.ts file is not available? For instance, can I incorpora ...

Finding keys corresponding to specific values in an object using Typescript

I have a straightforward scenario in mind. I am looking to create a function called pluckOnlyStringValues that takes an object obj and a key. The main requirement is that the key passed should correspond to a string value in the object, ensuring that pluck ...

Is the naming convention for parameterized types (T, U, V, W) in Generics adhered to by Typescript?

Is TypeScript following the same naming convention for parameterized types as other languages like C++ and Java, using T,U,V,W, or is there a mixed usage of conventions? In the TS 2.8 release notes, we see examples like: type ReturnType<T> = T exten ...

What could be causing the error in Angular Universal Server Side Rendering after deployment on Firebase Hosting?

Currently immersed in Angular development utilizing third-party libraries such as Angular CLI/Angular Universal, following the guidelines laid out here. Also, integrating Firebase hosting and real-time database. The application works flawlessly on my local ...

Guide to defining a typescript class property using an index signature

type TField = { field1: string; field2: boolean; field3: TMyCustom; } class Test1 { // I opt for using TypeScript's index signature to declare class fields [key: keyof TField]: TField[typeof key] // Instead of individually declaring each ...

There has been a mistake: "Unable to locate a suitable differ supporting object '[object Object]' of type 'object'. NgFor is only able to bind to Iterables like Arrays."

Currently facing an issue: I am trying to extract the values of "place" using ngFor directive. Here's what I have implemented: .html <ng-container *ngFor="let se of List" Here is the JSON data: .json "place": [ { &qu ...

Fire the BehaviorSubject with the identical value following a mutation

I am working with a BehaviorSubject where I have to make changes through mutation (for reasons beyond my control). I need to trigger the BehaviorSubject for subscriptions whenever there are changes. Is there another approach I can take instead of using: ...

"Compilation errors encountered when trying to build Typescript within a Azure Function App running in

Currently, I am in the process of deploying to an Azure Function App from a container that resides inside Azure Container Registry. To begin with, I utilized the func init command (selected the typescript option) and incorporated some code using the servi ...

The presence of catchError() within the pipe() function will display an error specifically at the .subscribe stage

I encountered an issue while trying to handle errors for a method in Angular. After adding a catchError check using the .pipe() method, I noticed that the variable roomId was marked with a red squiggly line. The error message read: TS2345: Argument of type ...

Generating Tree Structure Object Automatically from Collection using Keys

I am looking to automatically generate a complex Tree structure from a set of objects, with the levels of the tree determined by a list of keys. For example, my collection could consist of items like [{a_id: '1', a_name: '1-name', b_id ...

The module './product' could not be located, resulting in error TS2307

app/product-detail.component.ts(2,22): error TS2307: Cannot find module './product'. I have tried several solutions but none of them seem to work for me. I am working on a demo app in Angular 2 and encountering this specific error. Any guidance ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

Pre-loading custom fonts in Next.js for a smoother user experience

I am currently utilizing next.js. My objective is to ensure that the fonts are loaded before any content is displayed on the screen. I attempted to achieve this by including them in the Head component within the _.document file using the rel="prelo ...

Creating a definition for the use of sweet alerts within a service and incorporating them through

Implementing sweet alert for displaying alert messages in angularJS2/typescript. Due to the repetitive nature of this code in different parts of the application, a service was created. @Injectable() export class AlertMessageService { constructor(pr ...

Testing the functionality of an event that is not linked to an event emitter

Below is the code snippet I'm working with: private client: any; this.client = mqtt.connect(url, mqttOptions); this.client.on('message', (topic: string, message: string) => { console.log('came inside onMessage'); ...

Encounter an Unexpected Token Issue when using NextJS-auth0 in Jest

I am facing a problem with my Next.js app that is integrated with the nextjs-auth0 package. Whenever I attempt to test a particular file and include the following import: import { getSession } from '@auth0/nextjs-auth0'; An error occurs, stating ...

a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to ...