Ways to change a value into int8, int16, int32, uint8, uint16, or uint32

In TypeScript, the number variable is floating point by default. However, there are situations where it's necessary to restrict the variable to a specific size or type similar to other programming languages. For instance, types like int8, int16, int32, uint8, uint16, and uint32. The approach I've taken involves converting the number to an unsigned integer and performing bitwise operations accordingly. If there are any improvements, better methods, or more efficient ways to achieve this, please share.


export class CONVERT {
   static NumberToUint32(x: number): number 
   {
      return x >>> 0;
   }
   static NumberToUint16(x: number): number 
   {
      return this.NumberToUint32(x) & 0xFFFF;
   }
   static NumberToUint8(x: number): number 
   {
      return this.NumberToUint32(x) & 0xFF;
   }

   static NumberToInt32(x: number): number
   {
      return x >> 0;
   }
   static NumberToInt16(x: number): number
   {
      let r: number = 0; 
      let n = this.NumberToUint16(x);
      if(n & 0x8000)
         r =  0xFFFF8000 | (n & 0x7FFF);
      else
         r = n;         
      return(r);      
   }
   static NumberToInt8(x: number): number
   {      
      let r: number = 0; 
      let n = this.NumberToUint8(x);
      if(n & 0x80)
         r =  0xFFFFFF80 | (n & 0x7F); 
      else
         r = n;     
      return(r);      
   }      

   static StrToNumber(val: string, defaultVal: number = 0): number
   {        
      let result: number = defaultVal;      
      if(!val || val.trim().length == 0) 
         return result;

      // Code for converting string to number
   }
}

Answer №1

TypeScript lacks more specific numerical types beyond bigint or number because enforcing such constraints in a JavaScript-based type system would be challenging. More information on this can be found at https://example.com/typescript-numeric-types-issue.

If you are determined to enforce distinct numeric types, one option is to use a unique "branded type," similar to what is offered by https://example.com/branded-types-js. Branded numeric types essentially inform the type system that a type alias refers to number as well as a hypothetical "brand" property:

type Int16 = number & { __brand: "int16" };

To convert a value into a branded type, typically an as assertion or type predicate would be used:

const fiveAsInt16 = 5 as Int16;

The benefit of branded types is that TypeScript prohibits assigning any arbitrary number-typed value to a variable with type Int16. Only values labeled as "int16" can be assigned.

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

jQuery ajaxSetup: handling error retries for ajax calls is not possible

When using $.ajaxSetup(), I am faced with the challenge of making an AJAX request after refreshing a valid token in case the previous token has expired. The issue arises when attempting to execute $.ajax(this) within the error callback. $.ajax({ url: ...

Choose an XPath selector that targets a list item within a specific div element

Currently, I am using selenium to conduct testing on a website. I have employed an XPath selector in order to locate a specific item within the HTML structure: <div id="boundlist-1051" class="x-boundlist list_cfg_cls x-boundlist-floating x-layer x-boun ...

Angular 13.0 version is experiencing issues when trying to run the "ng serve" command

After installing the npm module, I encountered a problem while using node.js version 14.17.6. I am a beginner in Angular and struggling to find a solution due to not using the latest Angular CLI version. Any help would be greatly appreciated. Thank you in ...

What is the correct way to promise-ify a request?

The enchanting power of Bluebird promises meets the chaotic nature of request, a function masquerading as an object with methods. In this straightforward scenario, I find myself with a request instance equipped with cookies via a cookie jar (bypassing req ...

The app.html for the skygear/react-chat-demo is malfunctioning

I followed the instructions provided in the Skygear manual at https://docs.skygear.io/guides/advanced/server/ The skygear-server-darwin-amd64 started successfully. Then, I attempted to run the react-chat-demo project from https://github.com/skygear-de ...

Why is the format incorrect when the Angular 7 (Change)-Function on Input of type Date isn't functioning?

I am facing an issue with updating the date using key input and assigning the selected date to a property of my object. Below is the code I'm currently working with: <input type="date" [value]="dateTime()" (change)="setDate($event)"/> The dat ...

Create categories for static array to enable automatic suggestions

I have a JavaScript library that needs to export various constants for users who are working with vscode or TypeScript. The goal is to enable auto-complete functionality for specific constant options. So far, I've attempted to export a Constant in th ...

Creating an easy-to-update catalog utilizing an external file: A step-by-step guide

I am looking to create a product catalog with 1-4 products in a row, each displayed in a box with details and prices. I would like to be able to generate the catalog easily using an XML/CSV file that can be updated. Can anyone provide guidance on how to ac ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

Selecting elements dynamically with JQuery

Trying to use a jQuery selector within plugin code created by a 3rd party has proved difficult. When hardcoded, it works fine; however, when attempting to use variables for dynamic selection, the object cannot be found. The lack of id handles in the CSS c ...

Ways to verify if two items within a collection of objects share a common value in MongoDB

I have a collection of data called users stored in mongoDB that has the following structure: _id: ObjectId, sports: [ { name: 'cricket', history: [ { from: 10, to: 30 }, { from: 30, to: ...

Using Kendo TabStrip to dynamically include HTML files as tabs

In the process of creating a web-part that mirrors a Kendo tabstrip, I've managed to integrate a simple ul with external html files linked to each relative li using JavaScript. The functionality works smoothly up until this point. However, my current ...

Solve the problem with SCSS at the component level in NextJS

I've decided to transition my regular React app to Next.js. In the past, I would simply import SCSS files using: import from '.componentName.scss' However, now I need to import them using: import style from 'componentName.module.scss ...

Error: Module specifier "react-router-dom" could not be resolved. Relative references should start with either "/", "./", or "../"

I encountered an error message after executing the command npm run preview: Uncaught TypeError: Failed to resolve module specifier "react-router-dom". Relative references must start with either "/", "./", or "../". ...

Using jQuery to restrict users from entering a character consecutively more than three times within a single word

Is there a way to restrict users from repeating the same character more than three times in a single word? For example, allowing "hiii" but not "hiiii" to be typed in a textbox? I am looking for something similar to how the textbox works on this website f ...

Is it possible to pass a variable to a text constant in Angular?

In my constant file, I keep track of all global values. Here is the content of the file: module.exports = { PORT: process.env.PORT || 4000, SERVER: "http://localhost:4200", FAIL_RESULT: "NOK", SUCCESSFUL_RESULT: "OK ...

Using Vue's computed property setter with an object as a prop

I have a new concept for an input component where different objects can be passed, displayed as CSV, and allow for text editing/validation with style changes based on validation results. Check out the code snippet I've been working on: <div id=&quo ...

Error: The token 'export' in d3zoom is causing a syntax issue

I'm encountering issues with executing tests in Angular: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export {default as zoom} from "./zoom.js"; ...

troubleshooting Axios errors in React applications

User/Project.js: import React, { useState, useEffect } from "react"; import Axios from "axios"; const Project = () => { const [projectName, setprojectName] = useState(""); const [projectDescription, setprojectDescriptio ...

Dynamic jQuery Carousel

Is there a jQuery slider that can adapt to different screen sizes and handle images of varying widths? Appreciate any insights! ...