如何在typescript中检查子字符串是否与字符串列表中的某个匹配

ee7vknir  于 2022-12-14  发布在  TypeScript
关注(0)|答案(1)|浏览(215)

让我们考虑一个例子

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');

如何编写BeforeSign泛型类型以使所有handleRoute调用都没有错误?

gpnt7bae

gpnt7bae1#

您可以使用 template literal type 将字符串文字连接在一起。

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

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

Playground

相关问题