我要打1-2打。
代码如下:
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');
我希望以下所有三项检查都能通过。
我也一直在使用这种强制转换字符串的方法,但是我无法在运行时检查变量的类型。
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;
}
答案 0 :(得分:0)
实际上,请忽略我之前关于原始数据类型和对象不同的评论,我自己对此进行了测试,所有测试都通过了吗? ...
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>