1

I would like to create some new string types in TypeScript that will show an error if it does not match a pattern. For example, I would like to create these types that will match a regex pattern.

type UnixFilesystemPath = '/something/something/something'
type WindowsFilesystemPath = 'X:\something\something'
type FtpPath = 'ftp://something/something'

let unixFile = 'test'                   // error
let unixFile = '/home/martin/script.sh' // ok
let unixFile = '/var/'                  // ok

Is this possible with TypeScript?

martins16321
  • 591
  • 1
  • 5
  • 15

1 Answers1

0

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.
martins16321
  • 591
  • 1
  • 5
  • 15