2

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.