Everettss
Everettss

Reputation: 16049

How in typescript check if substring match one of in list of strings

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?

Upvotes: 1

Views: 204

Answers (1)

Tobias S.
Tobias S.

Reputation: 23865

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

Upvotes: 2

Related Questions