Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom String class

I am looking for a 1-2 punch.

  1. I'd like to typecast custom strings.
  2. Within runtime I'd like to be able to know the type of a string different from a primitive string.

Here's the 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 would like all three of the checks below to pass.

I also have been messing with this method of casting strings as well but I have no way of checking in runtime the type of the variable.

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;
}
like image 914
ThomasReggi Avatar asked Mar 18 '26 22:03

ThomasReggi


1 Answers

Actually, ignore my previous comments about the primitive datatype and object being different, I just tested this myself, and all tests pass? ...

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>