javascript - ¿Cómo crear un tipo en TypeScript que coincida con una cadena contra una expresión regular?
Me gustaría crear algunos nuevos tipos de cadenas en TypeScript que muestren un error si no coinciden con un patrón. Por ejemplo, me gustaría crear estos tipos que coincidan con un patrón regex.
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
¿Es esto posible con TypeScript?
Respuesta #1
Después de investigar mucho, parece que la única solución (que he encontrado) es crear clases personalizadas para este tipo de "tipos". Por ejemplo, si quisiera un tipo UnixAbsolutePath, entonces podría crear algo así.
Por favor corrígeme si me equivoco o si hay una mejor solución. El único problema con esto es que cuando intentas setPath() no generará un error de compilación sino solo un error en tiempo de ejecución.
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.
