After much digging around, it seems that the only solution (that I've found) is to create custom classes for these kinds of "types". For example, if I wanted a UnixAbsolutePath
type then I could create something like this.
Please correct me if I'm wrong or if there is a better solution. The one problem with this is that when you try to setPath()
it will not throw a compilation error but only a runtime error.
class UnixAbsolutePath {
/**
* Unix Absolute Path
* Can be a path to a directory or a path to a file.
*
* Examples: /bin/bash, /var/log/
*/
private path: string
constructor(path: string) {
this.path = this.validated(path)
}
public getPath(): string {
return this.path
}
public setPath(path: string): void {
this.path = this.validated(path)
}
private validated(path: string): string {
const regex = new RegExp('^(/[^/ ]*)+/?$')
if (!regex.test(path)) {
throw new TypeError(`${path} is not a valid unix filesystem path.`)
}
return path
}
}
let bashPath: UnixAbsolutePath = new UnixAbsolutePath('/bin/bash')
console.log(bashPath.getPath()) // [LOG]: "/bin/bash"
bashPath = 'myfile.sh' // Type 'string' is not assignable to type 'UnixAbsolutePath'
bashPath.setPath('myfile.sh') // Only runtime error - myfile.sh is not a valid unix filesystem path.