Unverified Commit 6ae1e1b3 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[strict-route-types] Typecheck App Router page props (#87386)

parent 5cddef4f
...@@ -739,14 +739,14 @@ export function generateValidatorFileStrict( ...@@ -739,14 +739,14 @@ export function generateValidatorFileStrict(
if (appPageValidations) { if (appPageValidations) {
typeDefinitions += `type AppPageConfig<Route extends AppRoutes = AppRoutes> = { typeDefinitions += `type AppPageConfig<Route extends AppRoutes = AppRoutes> = {
default: React.ComponentType<{ params: Promise<ParamMap[Route]> } & any> | ((props: { params: Promise<ParamMap[Route]> } & any) => React.ReactNode | Promise<React.ReactNode> | never | void | Promise<void>) default: React.ComponentType<PageProps<Route>> | ((props: PageProps<Route>) => React.ReactNode | Promise<React.ReactNode> | never | void | Promise<void>)
generateStaticParams?: (props: { params: ParamMap[Route] }) => Promise<any[]> | any[] generateStaticParams?: (props: { params: ParamMap[Route] }) => Promise<any[]> | any[]
generateMetadata?: ( generateMetadata?: (
props: { params: Promise<ParamMap[Route]> } & any, props: PageProps<Route>,
parent: ResolvingMetadata parent: ResolvingMetadata
) => Promise<any> | any ) => Promise<any> | any
generateViewport?: ( generateViewport?: (
props: { params: Promise<ParamMap[Route]> } & any, props: PageProps<Route>,
parent: ResolvingViewport parent: ResolvingViewport
) => Promise<any> | any ) => Promise<any> | any
metadata?: any metadata?: any
...@@ -994,6 +994,7 @@ export function generateRouteTypesFileStrict( ...@@ -994,6 +994,7 @@ export function generateRouteTypesFileStrict(
// Build export statement based on what's actually generated // Build export statement based on what's actually generated
const routeExports = [ const routeExports = [
'AppRoutes', 'AppRoutes',
'PageProps',
'PageRoutes', 'PageRoutes',
'LayoutRoutes', 'LayoutRoutes',
'RedirectRoutes', 'RedirectRoutes',
......
...@@ -5,7 +5,7 @@ import { getSentinelValue } from '../../getSentinelValue' ...@@ -5,7 +5,7 @@ import { getSentinelValue } from '../../getSentinelValue'
export default async function Page({ export default async function Page({
searchParams: _unused, searchParams: _unused,
}: { }: {
searchParams: Promise<{ n: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) { }) {
return ( return (
<> <>
......
...@@ -22,10 +22,10 @@ async function validateSlug(slug: string[]) { ...@@ -22,10 +22,10 @@ async function validateSlug(slug: string[]) {
export default async function CatchAll({ export default async function CatchAll({
params, params,
}: { }: {
params: Promise<{ slug: string[] }> params: Promise<{ slug?: string[] }>
}) { }) {
const { slug } = await params const { slug } = await params
const slugArray = Array.isArray(slug) ? slug : [slug] const slugArray = Array.isArray(slug) ? slug : []
// Validate the slug // Validate the slug
const isValid = await validateSlug(slugArray) const isValid = await validateSlug(slugArray)
......
...@@ -5,7 +5,7 @@ import { useRouter } from 'next/navigation' ...@@ -5,7 +5,7 @@ import { useRouter } from 'next/navigation'
export default function Page({ export default function Page({
params, params,
}: { }: {
params: Promise<{ dynamic: string }> params: Promise<{ dynamic: string[] }>
}) { }) {
const router = useRouter() const router = useRouter()
return ( return (
......
...@@ -5,7 +5,7 @@ import { useRouter } from 'next/navigation' ...@@ -5,7 +5,7 @@ import { useRouter } from 'next/navigation'
export default function Page({ export default function Page({
params, params,
}: { }: {
params: Promise<{ dynamic: string }> params: Promise<{ dynamic: string[] }>
}) { }) {
const router = useRouter() const router = useRouter()
return ( return (
......
...@@ -6,10 +6,10 @@ import { revalidateTag } from 'next/cache' ...@@ -6,10 +6,10 @@ import { revalidateTag } from 'next/cache'
const RevalidateViaPage = async ({ const RevalidateViaPage = async ({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ tag: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) => { }) => {
const { tag } = await searchParams const { tag } = await searchParams
revalidateTag(tag, 'max') revalidateTag(tag as any, 'max')
return ( return (
<div className="flex flex-col items-center justify-center h-screen"> <div className="flex flex-col items-center justify-center h-screen">
......
...@@ -7,7 +7,7 @@ function Content({ ...@@ -7,7 +7,7 @@ function Content({
searchParams, searchParams,
}: { }: {
params: Promise<{ product: string }> params: Promise<{ product: string }>
searchParams: Promise<{ foo: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) { }) {
const { product } = use(params) const { product } = use(params)
const searchParamsDict = use(searchParams) const searchParamsDict = use(searchParams)
...@@ -30,7 +30,7 @@ export default function ProductPage({ ...@@ -30,7 +30,7 @@ export default function ProductPage({
searchParams, searchParams,
}: { }: {
params: Promise<{ product: string }> params: Promise<{ product: string }>
searchParams: Promise<{ foo: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) { }) {
return ( return (
<Suspense fallback="Loading..."> <Suspense fallback="Loading...">
......
...@@ -2,7 +2,11 @@ ...@@ -2,7 +2,11 @@
import { Suspense, use } from 'react' import { Suspense, use } from 'react'
function Content({ searchParams }: { searchParams: Promise<{ foo: string }> }) { function Content({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>
}) {
const searchParamsDict = use(searchParams) const searchParamsDict = use(searchParams)
let query = null let query = null
...@@ -20,7 +24,7 @@ function Content({ searchParams }: { searchParams: Promise<{ foo: string }> }) { ...@@ -20,7 +24,7 @@ function Content({ searchParams }: { searchParams: Promise<{ foo: string }> }) {
export default function ClientPageWithSearchParam({ export default function ClientPageWithSearchParam({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ foo: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) { }) {
return ( return (
<Suspense fallback="Loading..."> <Suspense fallback="Loading...">
......
...@@ -2,9 +2,10 @@ import { nextTestSetup } from 'e2e-utils' ...@@ -2,9 +2,10 @@ import { nextTestSetup } from 'e2e-utils'
import { getDistDir } from 'next-test-utils' import { getDistDir } from 'next-test-utils'
describe('typed-routes-validator', () => { describe('typed-routes-validator', () => {
const { next, isNextStart, skipped } = nextTestSetup({ const { next, isNextDev, isNextStart, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
skipDeployment: true, skipDeployment: true,
skipStart: true,
}) })
if (skipped) { if (skipped) {
...@@ -12,6 +13,11 @@ describe('typed-routes-validator', () => { ...@@ -12,6 +13,11 @@ describe('typed-routes-validator', () => {
} }
it('should generate route validation correctly', async () => { it('should generate route validation correctly', async () => {
if (isNextDev) {
await next.start()
} else {
await next.build()
}
const dts = await next.readFile(`${getDistDir()}/types/validator.ts`) const dts = await next.readFile(`${getDistDir()}/types/validator.ts`)
// sanity check that dev generation is working // sanity check that dev generation is working
expect(dts).toContain('const handler = {} as typeof import(') expect(dts).toContain('const handler = {} as typeof import(')
...@@ -19,7 +25,6 @@ describe('typed-routes-validator', () => { ...@@ -19,7 +25,6 @@ describe('typed-routes-validator', () => {
if (isNextStart) { if (isNextStart) {
it('should pass type checking with valid page exports', async () => { it('should pass type checking with valid page exports', async () => {
await next.stop()
await next.patchFile( await next.patchFile(
'app/test-page.tsx', 'app/test-page.tsx',
` `
...@@ -37,7 +42,6 @@ describe('typed-routes-validator', () => { ...@@ -37,7 +42,6 @@ describe('typed-routes-validator', () => {
}) })
it('should fail type checking with invalid page exports', async () => { it('should fail type checking with invalid page exports', async () => {
await next.stop()
await next.patchFile( await next.patchFile(
'app/invalid/page.tsx', 'app/invalid/page.tsx',
` `
...@@ -56,8 +60,44 @@ describe('typed-routes-validator', () => { ...@@ -56,8 +60,44 @@ describe('typed-routes-validator', () => {
) )
}) })
it('should pass type checking with valid page props', async () => {
await next.patchFile(
'app/valid/[id]/page.tsx',
`
export default function ValidPage(props: { params: Promise<{ id: string }> }) {
return <div>Valid Page</div>
}
`
)
const { exitCode } = await next.build()
// clean up before assertion just in case it fails
await next.deleteFile('app/valid/[id]/page.tsx')
expect(exitCode).toBe(0)
})
it('should fail type checking with invalid page props', async () => {
await next.patchFile(
'app/invalid/page.tsx',
`
export default function InvalidPage(props: { invalidProp: string }) {
return <div>Invalid Page</div>
}
`
)
const { exitCode, cliOutput } = await next.build()
// clean up before assertion just in case it fails
await next.deleteFile('app/invalid/page.tsx')
expect(exitCode).toBe(1)
expect(cliOutput).toMatch(
/Type error: Type 'typeof import\(.*' does not satisfy the constraint 'AppPageConfig</
)
})
it('should pass type checking with valid route handler exports', async () => { it('should pass type checking with valid route handler exports', async () => {
await next.stop()
await next.patchFile( await next.patchFile(
'app/valid/route.ts', 'app/valid/route.ts',
` `
...@@ -95,7 +135,6 @@ describe('typed-routes-validator', () => { ...@@ -95,7 +135,6 @@ describe('typed-routes-validator', () => {
}) })
it('should fail type checking with invalid route handler return type', async () => { it('should fail type checking with invalid route handler return type', async () => {
await next.stop()
await next.patchFile( await next.patchFile(
'app/invalid/route.ts', 'app/invalid/route.ts',
` `
...@@ -117,7 +156,6 @@ describe('typed-routes-validator', () => { ...@@ -117,7 +156,6 @@ describe('typed-routes-validator', () => {
}) })
it('should fail type checking with invalid route handler params', async () => { it('should fail type checking with invalid route handler params', async () => {
await next.stop()
await next.patchFile( await next.patchFile(
'app/invalid-2/route.ts', 'app/invalid-2/route.ts',
` `
...@@ -139,7 +177,6 @@ describe('typed-routes-validator', () => { ...@@ -139,7 +177,6 @@ describe('typed-routes-validator', () => {
}) })
it('should pass type checking with valid layout exports', async () => { it('should pass type checking with valid layout exports', async () => {
await next.stop()
await next.patchFile( await next.patchFile(
'app/test/layout.tsx', 'app/test/layout.tsx',
` `
...@@ -160,7 +197,6 @@ describe('typed-routes-validator', () => { ...@@ -160,7 +197,6 @@ describe('typed-routes-validator', () => {
}) })
it('should fail type checking with invalid layout exports', async () => { it('should fail type checking with invalid layout exports', async () => {
await next.stop()
await next.patchFile( await next.patchFile(
'app/invalid/layout.tsx', 'app/invalid/layout.tsx',
` `
...@@ -182,7 +218,6 @@ describe('typed-routes-validator', () => { ...@@ -182,7 +218,6 @@ describe('typed-routes-validator', () => {
}) })
it('should pass type checking with valid API route exports', async () => { it('should pass type checking with valid API route exports', async () => {
await next.stop()
await next.patchFile( await next.patchFile(
'pages/api/valid-api.ts', 'pages/api/valid-api.ts',
` `
...@@ -208,7 +243,6 @@ describe('typed-routes-validator', () => { ...@@ -208,7 +243,6 @@ describe('typed-routes-validator', () => {
}) })
it('should fail type checking with invalid API route exports', async () => { it('should fail type checking with invalid API route exports', async () => {
await next.stop()
await next.patchFile( await next.patchFile(
'pages/api/invalid-api.ts', 'pages/api/invalid-api.ts',
` `
......
export default async function Page({ export default async function Page({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ [key: string]: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) { }) {
'use cache: private' 'use cache: private'
......
...@@ -10,9 +10,9 @@ async function getCached({ p }) { ...@@ -10,9 +10,9 @@ async function getCached({ p }) {
export default async function Page({ export default async function Page({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ n: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) { }) {
const n = parseInt((await searchParams).n, 16) const n = parseInt((await searchParams).n as any, 16)
const p = Promise.resolve(new Uint8Array([n])) const p = Promise.resolve(new Uint8Array([n]))
return <p id="x">{await getCached({ p })}</p> return <p id="x">{await getCached({ p })}</p>
} }
...@@ -10,9 +10,9 @@ async function getCachedRandom(x: number, children: React.ReactNode) { ...@@ -10,9 +10,9 @@ async function getCachedRandom(x: number, children: React.ReactNode) {
export default async function Page({ export default async function Page({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ n: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) { }) {
const n = +(await searchParams).n const n = +(await searchParams).n!
const values = await getCachedRandom( const values = await getCachedRandom(
n, n,
<p id="r">rnd{Math.random()}</p> // This should not invalidate the cache <p id="r">rnd{Math.random()}</p> // This should not invalidate the cache
......
export function withSlug<P extends { params: Promise<{ slug: string }> }>( export function withSlug(
Component: React.ComponentType<{ slug: string }> Component: React.ComponentType<{ slug: string }>
): React.ComponentType<{ params: Promise<{ slug: string }> }> { ): // TODO(NXT-127): Use ComponentType
return async function ComponentWithSlug(props: P) { React.JSXElementConstructor<{ params: Promise<{ slug: string }> }> {
return async function ComponentWithSlug(props: {
params: Promise<{ slug: string }>
}) {
const params = await props.params const params = await props.params
const slug = params.slug const slug = params.slug
......
...@@ -13,9 +13,9 @@ async function getCachedRandom(x: number, children: React.ReactNode) { ...@@ -13,9 +13,9 @@ async function getCachedRandom(x: number, children: React.ReactNode) {
export default async function Page({ export default async function Page({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ n: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) { }) {
const n = +(await searchParams).n const n = +(await searchParams).n!
const values = await getCachedRandom( const values = await getCachedRandom(
n, n,
<p id="r">rnd{Math.random()}</p> // This should not invalidate the cache <p id="r">rnd{Math.random()}</p> // This should not invalidate the cache
......
export default async function Page({ export default async function Page({
searchParams, searchParams,
}: { }: {
searchParams: Promise<{ id: string }> searchParams: Promise<Record<string, string | string[] | undefined>>
}) { }) {
const { id } = await searchParams const { id } = await searchParams
return <p>hello world {id}</p> return <p>hello world {id}</p>
......
...@@ -55,7 +55,7 @@ describe('types-gen-nounuselocal', () => { ...@@ -55,7 +55,7 @@ describe('types-gen-nounuselocal', () => {
} }
export type { AppRoutes, PageRoutes, LayoutRoutes, RedirectRoutes, RewriteRoutes, ParamMap } export type { AppRoutes, PageProps, PageRoutes, LayoutRoutes, RedirectRoutes, RewriteRoutes, ParamMap }
declare global { declare global {
/** /**
......
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