Unverified Commit 1c83bb86 authored by Ngô Đức Anh's avatar Ngô Đức Anh Committed by GitHub

Fix(typedRoutes): fixed empty DynamicRoutes or StaticRoutes causing Route to…

Fix(typedRoutes): fixed empty DynamicRoutes or StaticRoutes causing Route to turn into type string (#46980)



Fixes #46974

When `dynamicRouteTypes` or `staticRouteTypes` is empty, type `DynamicRoutes`/`StaticRoutes` fallbacks to type `string`, causing type `Route` to resolve to type `string` as well, meaning that the user can use any string as `href`. This fixes that by making those types fallback to type `never` instead, and if both `dynamicRouteTypes` and `staticRouteTypes` are empty, fallback to type `string`.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent cbc511ba
......@@ -257,6 +257,10 @@ function createRouteDefinitions() {
dynamicRouteTypes += routeTypes[type].dynamic
}
// If both StaticRoutes and DynamicRoutes are empty, fallback to type 'string'.
const routeTypesFallback =
!staticRouteTypes && !dynamicRouteTypes ? 'string' : ''
return `// Type definitions for Next.js routes
/**
......@@ -286,17 +290,22 @@ declare namespace __next_route_internal_types__ {
type OptionalCatchAllSlug<S extends string> =
S extends \`\${string}\${SearchOrHash}\` ? never : S
type StaticRoutes = ${staticRouteTypes || 'string'}
type StaticRoutes = ${staticRouteTypes || 'never'}
type DynamicRoutes<T extends string = string> = ${
dynamicRouteTypes || 'string'
dynamicRouteTypes || 'never'
}
type RouteImpl<T> =
type RouteImpl<T> = ${
routeTypesFallback ||
`
${
/* This keeps autocompletion working for static routes */ '| StaticRoutes'
// This keeps autocompletion working for static routes.
'| StaticRoutes'
}
| \`\${StaticRoutes}\${Suffix}\`
| (T extends \`\${DynamicRoutes<infer _>}\${Suffix}\` ? T : never)
`
}
}
declare module 'next' {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment