Home > other >  How in typescript check if substring match one of in list of strings
How in typescript check if substring match one of in list of strings

Time:12-13

Let's consider example

type Routes = 'first' | 'second';

type BeforeSign = //...

const handleRoute = (route: BeforeSign<Routes, '#'>) => route;

handleRoute('first');
handleRoute('first#additional');
handleRoute('first#random');
handleRoute('second#example');

// @ts-expect-error
handleRoute('third');
// @ts-expect-error
handleRoute('third#nope');

How to write BeforeSign generic type to make all handleRoute calls without error?

CodePudding user response:

You can use a template literal type to concatenate the string literal together.

type BeforeSign<R extends string, D extends string> = R | `${R}${D}${string}` 

const handleRoute = (route: BeforeSign<Routes, '#'>) => route;

Playground

  • Related