Bespoke String Implementation

Can someone help me find a dual approach?

  1. I am interested in customizing strings based on type.
  2. I want to be able to determine the type of a string different from a primitive string during runtime.

Take a look at this code:

class TZDatabaseName extends String {
  constructor(...args) {
    super(...args);
    return this;
  }
}

expect(new TZDatabaseName('Asia/Tokyo') instanceof String).toBeTruthy();
expect(new TZDatabaseName('Asia/Tokyo') instanceof TZDatabaseName).toBeTruthy();
expect(new TZDatabaseName('Asia/Tokyo')).toEqual('Asia/Tokyo');

I aim for all three checks below to succeed.

I've also been experimenting with string casting, but I'm struggling to verify the variable's type during runtime.

export abstract class TZDatabaseName extends String {
  public static MAKE(s: string): TZDatabaseName {
    if (!s.match(/^\w+\/\w+$/)) throw new Error('invalid TZDatabaseName');
    return s as any;
  }
  private __TZDatabaseNameFlag;
}

Answer №1

After further testing, I have realized that my previous assertion about the differences between primitive datatype and object was incorrect. Upon conducting tests myself, all tests actually pass without any issues.

class TZDatabaseName extends String {
  constructor(...args) {
    super(...args);
    return this;
  }
}


describe('TZDatabaseName', function() {
  it('Instance of String', function() {
    expect(new TZDatabaseName('Asia/Tokyo') instanceof String).toBeTruthy();
  });

  it('Instance of TZDatabaseName', function() {
    expect(new TZDatabaseName('Asia/Tokyo') instanceof TZDatabaseName).toBeTruthy();
  });

  it('Equal to Primitive Type', function() {
    expect(new TZDatabaseName('Asia/Tokyo')).toEqual('Asia/Tokyo');
  });
});


describe('More TZDatabaseName', function() {
  it('Primitive Instance of TZDatabaseName', function() {
    expect('')
      instanceof TZDatabaseName).toBeFalsy();
  });

  it('Primitive Instance of String', function() {
    expect('')
      instanceof String).toBeFalsy();
  });

  it('String Instance of TZDatabaseName', function() {
    expect(String('') instanceof TZDatabaseName).toBeFalsy();
  });
});


// Jasmine htmlReporter
(function() {
  var env = jasmine.getEnv();
  env.addReporter(new jasmine.HtmlReporter());
  env.execute();
}());
<link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" />
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>

Answer №2

Reflecting on this after a few years, my new approach would be:

class TZDatabaseName extends String {
  constructor(...args) {
    super(...args);
    if (!s.match(/^\w+\/\w+$/)) {
      throw new Error('invalid TZDatabaseName');
    }
    return this;
  }
}

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 function 'downloadFunc' is not recognized as a valid function within the context of ReactJS custom hooks

Here is a unique custom hook that triggers when the user presses a button, calling an endpoint to download files as a .zip: import { useQuery } from 'react-query'; import { basePath } from '../../config/basePath'; async function downlo ...

Ways to resolve cross-domain problems without the utilization of PHP

I have successfully implemented the code below, however I used demo.php to address the cross domain issue. How can I achieve this without using PHP, as the client prefers not to use it? $('#basic-search').submit(function(el){ var sear ...

Creating a personalized HTML email template with a TypeScript foreach loop

As I work on developing an app, users will have the opportunity to share product information via email. Each product includes a title, image, description, ingredients, and a list of energy values. Currently, I am able to send an email with all the product ...

React Native Material - Implementing a loading indicator upon button press

With React Native Material, I am trying to implement a loading feature when a button is clicked. The goal is to show the "loading" message only when the button is active, and hide it otherwise. Additionally, I would like for the loading message to disappea ...

Obtaining a return value from a function that involves a series of chained Ajax requests in jQuery

I'm facing an issue with my function that involves chained Ajax requests. Function A and B are both Ajax requests, where A runs first and B runs after A returns its data. The problem arises when Function C executes Function B. Upon execution of Funct ...

Difficulty Establishing a Connection with SQL Server Using TypeORM

My local machine is running an SQL Server instance, but I'm encountering an error when trying to connect a database from TypeORM. The error message reads: originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (seque ...

Unable to detect click event in Vue devtools

My component is supposed to detect if a menu item has a submenu and toggle its visibility accordingly. However, when I click on it, nothing happens and no event is registered in the Vue devtools. Despite following the Vue docs closely and using the same sy ...

JavaScript validation failing to validate number ranges for 4-digit numbers

Currently, I am facing an issue with validating numbers entered between two text boxes to ensure that the first number is not greater than the second number. The validation process seems to work fine for three-digit numbers (e.g., 800 - 900), but it fails ...

Issue with Magento: Unable to execute dataflow profiles due to Ajax Error (Uncaught TypeError: e is not a function)

Whenever I try to execute a dataflow profile in Magento, the following series of events unfold: The CSV file is uploaded successfully X rows are found A message displays: Starting ... :: saveRow (handler-method) However, a JavaScript error interrupts th ...

How can we merge all the values of keys within an object into a new array using ES6?

My objective is to transform dynamic data into an array based on the keys of the toolset object, which does not have a constant number of keys. { toolset:{ info1:{ event-date:{}, event-time:{}, }, info ...

Every second, I am dynamically updating a section of my HTML and populating it with data retrieved from a database

Struggling to constantly update a section of HTML with data from a database? The code isn't functioning properly and I'm in need of some assistance. In the first part of the code snippet, an HTML page calls an update function that makes an ajax c ...

Arranging Alphanumeric Characters in Typescript

Given input -> const s = ['2.1.1.a', '2.1.a', '2.1.1.d', 'A2.2', 'A2.1', 2.1.1.c', '2.1.b', '2.1.1.b'] Expected output after sorting -> const s = ['2.1.a', '2. ...

Troubleshooting: Datatables buttons not displaying properly in Bootstrap 4

My use of datatables with Bootstrap 4 includes the buttons extension for exporting table data. However, I am encountering an issue where the buttons do not appear on the page, and there are no errors in the console. My import statements are as follows: imp ...

Retrieving Vue component properties as a data type

I'm facing a dilemma with my Vue components. I want to extract the props from one component and use them as a type instead of a value in another component. Specifically, I have a component where I need to take in an array of props from a different com ...

Sending PHP form data to Google Chart via AJAX

After creating a PHP form drop-down list of table names in a database that captures the user's selection, I aim to use that selected table name to generate a Google chart. However, I'm encountering difficulties in passing the variable through AJA ...

Tips for presenting hierarchical information from my database in ejs

I'm currently working on a genealogy application using node js express and ejs but I'm facing an issue with displaying the database in order (starting from parent). This is the code snippet for retrieving my data and what I see when I log the ou ...

Can a file be transferred to the server using only client-side scripting via HTML, CSS, and JavaScript?

Currently, I am looking for a way to upload a file onto my server for personal use. The downloading part is sorted out, but the challenge lies in figuring out how to upload without relying on server side scripting. I have been able to find a solution tha ...

Encountering an issue while following the Amadeus JavaScript beginner's guide

I have recently started working with Amadeus and encountered a roadblock at the initial stage. I am using the test URL (test.api.amadeus.com). Upon implementing the example code with my API key and API secret, I am receiving the following error: ClientErro ...

Harnessing the Power of Google Tag Script in Next.js

After researching How to load Google Tag Manager with the next/script component (Next.js 11) and reviewing this documentation page, my issue remains unresolved. I am looking to implement Google Tag on multiple websites developed using nextjs, so I created ...

Is it possible to bind HTML within an AngularJS partial but encountering an inexplicable issue?

I'm facing an issue with my ng-repeat that involves using a partial HTML file to loop through and display items on a page. The variables within the partial are not displaying, but interestingly enough, the variable {{rule.name}} outside of the partial ...