I\'m looking for a better way to distinguish between different types of strings in my program- for example, absolute paths and relative paths. I want to be able to have func
abstract class RelativePath extends String {
public static createFromString(url: string): RelativePath {
// validate if 'url' is indeed a relative path
// for example, if it does not begin with '/'
// ...
return url as any;
}
private __relativePathFlag;
}
abstract class AbsolutePath extends String {
public static createFromString(url: string): AbsolutePath {
// validate if 'url' is indeed an absolute path
// for example, if it begins with '/'
// ...
return url as any;
}
private __absolutePathFlag;
}
var path1 = RelativePath.createFromString("relative/path");
var path2 = AbsolutePath.createFromString("/absolute/path");
// Compile error: type 'AbsolutePath' is not assignable to type 'RelativePath'
path1 = path2;
console.log(typeof path1); // "string"
console.log(typeof path2); // "string"
console.log(path1.toUpperCase()); // "RELATIVE/PATH"
This is just so wrong on every levels you could write a book about it... -- but it does work nicely, and it does get the job done.
Since their creation is controlled as such, AbsolutePath and RelativePath instances are:
String by the TS compiler, allowing string functions to be calledThis is analogous to a "faked inheritance" (as the TS compiler is told about an inheritance, but that inheritance does not exist at runtime) with additional data validation. Since no public members or methods were added, this should never cause unexpected runtime behavior, as the same supposed functionality exists both during compilation and runtime.