让我们考虑一个例子
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;
游乐场