Typescript type - exclude / ban special characters in 'string' type

Viewed 46

I would like to generate a type that allows only a specific format, but with only the standard letters / numbers - string seems to allow any string character.

// this is the type that is currently generated
type Path = `\path\${string}\page\random` | `\path\page\${string}`;

/*
Unfortunately, the above type allows all the below cases. 
But I don't want to accept anything with a ':' or a rogue '/' as well as meeting the above formats.
*/

// should be fine as params value has been resolved.
const path1: Path = '\path\hello\page\random';

// should be fine as params value has been resolved.
const path2: Path = '\path\page\somethingelse';

// should error - as it is a path with params (character ':' indicates param name)
const path3: Path = '\path\:id\page\random';

// should error - as it is a path with params (character ':' indicates param name)
const path4: Path = '\path\page\:param';

// should error too as there is an addition page '\' on the end
const path2: Path = '\path\page\somethingelse\and';

// Basically, I would like to ban the characters ':' and '/' from the 'string'.

1 Answers

Well, I couldn't find a non-generic type solution. So I made a dummy function that saves us from passing generic parameters around. I made 2 types one is for banning things from URL and the second one is for forcing the URL shape not containing banned types


type Banned = `${string}${':'|'/'}${string}`; // you can add more characters 
type GenericPath<T extends string> = `\\path\\${T extends Banned ? never : T}\\page\\random`

function getPath<T extends string>(str: GenericPath<T>): GenericPath<T> {
  return str;
}

Playground

Related