Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

type safe useParams #338

Open
xxleyi opened this issue Oct 16, 2022 · 0 comments
Open

type safe useParams #338

xxleyi opened this issue Oct 16, 2022 · 0 comments

Comments

@xxleyi
Copy link
Owner

xxleyi commented Oct 16, 2022

如何保证 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>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant