3 ms·
You can do much better than just a type alias in TypeScript, and get specializations of primitives that type check and compile away. type Path = string & {
by spankalee 8y ago
You can do much better than just a type alias in TypeScript, and get specializations of primitives that type check and compile away.
type Path = string & { _brand: never };
const Path = (s: string) => validatePath(s) as Path;
const p1: Path = Path('/foo/bar.js');
const p2: Path = '/foo/bar.js';
Here, p2 has an error because a string is not assignable to a Path.
- skybrian 8y agoThat's a neat trick! I went searching for articles about it and came up empty, though I did find other interesting uses of the "never" type.