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



让我们考虑一个例子

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调用没有错误?

您可以使用模板文字类型将字符串文字连接在一起。

type BeforeSign<R extends string, D extends string> = R | `${R}${D}${string}` 
const handleRoute = (route: BeforeSign<Routes, '#'>) => route;
游乐场

最新更新