Open xxleyi opened 1 year ago
如何保证 react router 中 useParams 的运行时和类型安全呢?还是有方法的。
type RouterParams<T extends string> = T extends `${'/' | ''}:${infer K}/${infer Rest}` ? { [k in K]: string } & RouterParams<`/${Rest}`> : T extends `/${infer _A}/${infer B}` ? RouterParams<`/${B}`> : {} function mathPath(path: string, fakeLocationPath?: string) { const locationPath = fakeLocationPath ?? location.pathname const regExp = new RegExp(path.split('/').map(v => v.startsWith(':') ? '.+' : v).join(`\/`)) return regExp.test(locationPath) } function useSafeParams<T extends string>(path: T): RouterParams<T> { if (process.Env.NODE_ENV === 'development') { if (!path || !mathPath(path)) { throw Error('不匹配当前 URL') } } return useParams() as RouterParams<T> }
如何保证 react router 中 useParams 的运行时和类型安全呢?还是有方法的。