Binary string type definition in Typescript

Is there a way to create a type that ensures each character is either '1' or '0' in JavaScript?

type Binary = '1'|'0'

The current type works for single characters only. Is it possible to create a type for repeating patterns of '1' and '0' characters?

Furthermore, I am interested in enforcing a specific length. The following implementation is all I could come up with:

type BinaryInput = `${Binary}${Binary}${Binary}${Binary}${Binary}`;

Answer №1

If you are looking for type safety at the interfaces of your API, consider utilizing a type that extends string and cannot be obtained without assertion (referred to as a "snowflake type"). You can then implement a type guard to validate the strings, or directly assert the type if you are certain and require the performance benefits of skipping the runtime check.

TS Playground link

type Binary<N extends number = number> = string & {
  readonly BinaryStringLength: unique symbol;
  length: N;
};

class AssertionError extends Error {
  name = 'AssertionError';
}

function assertIsBinaryString <L extends number>(
  str: string,
  length?: L,
): asserts str is Binary<L> {
  if (typeof length === 'number' && str.length !== length) {
    throw new AssertionError('Binary string has invalid length');
  }

  for (const unit of str) {
    if (unit !== '0' && unit !== '1') {
      throw new AssertionError('Invalid character in binary string');
    }
  }
}


// Implementation:

function asDecimal (bStr: Binary): number {
  return parseInt(bStr, 2);
}

function byteAsChar (byte: Binary<8>): string {
  return new TextDecoder().decode(new Uint8Array([asDecimal(byte)]));
}

let str = '00100100';
// console.log(asDecimal(str)); // string not assignable to Binary
/*                       ^^^
                      Error 2345 */

assertIsBinaryString(str);
console.log(asDecimal(str)); // now works correctly => 36

// console.log(byteAsChar(str)); // Binary<number> not assignable to Binary<8> because number not assignable to 8
/*                        ^^^
                      Error 2345 */

assertIsBinaryString(str, 8);
console.log(byteAsChar(str)); // now works correctly => "$"

Answer №2

Choosing branded types may be the optimal choice for your situation.


If you are storing binary data as a number, like this:

const myBinary = 0b1000;
typeof myBinary // 'number'

You have the option to create a branded primitive type for number:

type Binary = number & { readonly __brand: unique symbol };

To specify a specific length for the binary data:

type Binary<Length extends number> = number & { readonly __brand: unique symbol, length: Length }

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 use of findDOMNode has been marked as outdated in StrictMode. Specifically, findDOMNode was utilized with an instance of Transition (generated by MUI Backdrop) that is contained

I encountered the following alert: Alert: detectDOMNode is now outdated in StrictMode. detectDOMNode was given an instance of Transition which resides within StrictMode. Instead, attach a ref directly to the element you wish to reference. Get more inform ...

Showing data related to a certain value - what's the best way?

I am currently working on a page where I need to display and edit specific user information at /users/524.json. However, I also want to include the working days from another table on the same page. I have provided most of the code below for reference. Unfo ...

Unleash the power of a module by exposing it to the global Window object using the dynamic

In my development process, I am utilizing webpack to bundle and manage my TypeScript modules. However, I am facing a challenge where I need certain modules or chunks to be accessible externally. Can anyone guide me on how to achieve this? Additional conte ...

What is the best way to structure this React state container for modularity?

At my workplace, we have developed a state container hook for our React application and related packages. Before discussing what I'd like to achieve with this hook, let me provide some background information. Here is the functional code that's co ...

Encountering a 400 bad request error while trying to retrieve an authentication token from an API url in Angular

I encountered a problem in my Angular 6 application where I am receiving an Http 400 Bad Request error when attempting to call the API url for login token. The interesting thing is that the API works perfectly fine when accessed through POSTMAN. However, ...

Detecting changes in input text with Angular and Typescript

Searching for a straightforward and practical method to identify changes in my textfield has been challenging. Avoiding the use of (keypress) is necessary, as users may occasionally paste values into the field. The (onchange) event only triggers when the u ...

Enhancing TypeScript Native Interface Properties in TypeScript 2.4

After discovering an error in the native Typescript interface for HTMLTextAreaElement, I realized the need to make a correction. The current interface looks like this: interface HTMLTextAreaElement { setSelectionRange(start: number, end: number): void; ...

unable to automatically import React components from node modules

Recently, I began working with VS Code, utilizing Material UI with React and TypeScript. However, I am facing an issue where I am unable to import the components of Material UI using the alt(option) + enter shortcut on my Mac. The TypeScript version I am w ...

Tips for retrieving the Solana unix_timestamp on the front-end using JavaScript

Solana Rust smart contracts have access to solana_program::clock::Clock::get()?.unix_timestamp which is seconds from epoch (midnight Jan 1st 1970 GMT) but has a significant drift from any real-world time-zone as a result of Solana's processing delays ...

Error: Unable to access 'useRef' property of null object due to TypeError

Currently, I am using a combination of Next.js, TypeScript, sanity, and tailwindcss in my project. I have come across an error while attempting to utilize the react-hook-form. I have experimented with different approaches: Converting the Post function in ...

Retrieve TypeScript object after successful login with Firebase

I'm struggling with the code snippet below: login = (email: string, senha: string): { nome: string, genero: string, foto: string;} => { this.fireAuth.signInWithEmailAndPassword(email, senha).then(res => { firebase.database().ref(&ap ...

Creating a function in Typescript that transforms an array into a typed object

Recently, I have started learning TypeScript and I am working on a function to convert arrays from a web request response into objects. I have successfully written the function along with a passing unit test: import { parseDataToObject } from './Parse ...

Developing with TypeScript, Next.js, and Socket.io

Embarking on a new endeavor utilizing TypeScript, Next.js, and Socket.io has left me puzzled on how to integrate these technologies seamlessly. My project consists of the following files: /api/socket.ts: import { NextApiRequest, NextApiResponse } from &ap ...

Working with Typescript and JSX in React for event handling

I'm currently facing an issue with updating the state in a React component I'm developing using TypeScript (React with Addons 0.13.3, Typescript 1.6.0-dev.20150804, definition file from ). /// <reference path="react/react-addons.d.ts" /> i ...

Why am I unable to use a string as the src in next/image component?

After importing the Image module with the code import Image from "next/image";, I encountered an error that states: The type '{ src: string; }' cannot be assigned to type 'IntrinsicAttributes & ImageProps'. The type &apo ...

developing TypeScript classes in individual files and integrating them into Angular 2 components

We are currently putting together a new App using Angular2 and typescript. Is there a more organized method for defining all the classes and interfaces in separate files and then referencing them within angular2 components? import {Component, OnInit, Pi ...

Common mistakes made while working with decorators in Visual Studio Code

Having trouble compiling TypeScript to JavaScript when using decorators. A persistent error message I encounter is: app.ts:11:7 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ' ...

Angular CDK Overlay allows for bringing multiple overlays to the front effectively

Currently, I am experiencing an issue with Angular 15 where a click event placed within a mousedown event does not trigger. Interestingly, if the position of the element is not changed using appendChild, both the mousedown and click events work as expected ...

What is the process for attaching a function to an object?

Here is the complete code: export interface IButton { click: Function; settings?: IButtonSettings; } abstract class Button implements IButton { click() {} } class ButtonReset extends Button { super() } The component looks like this: expor ...

Using a Jasmine spy to monitor an exported function in NodeJS

I've encountered difficulties when trying to spy on an exported function in a NodeJS (v9.6.1) application using Jasmine. The app is developed in TypeScript, transpiled with tsc into a dist folder for execution as JavaScript. Application Within my p ...