Next Router与NextPage类型不兼容报错问题求助
解决Next.js动态路由中的TypeScript错误
问题场景
为原本仅支持静态路由的Next.js应用实现动态路由时,遇到TypeScript类型错误,代码及报错信息如下:
原代码
import { NextPage } from 'next'; import { useRouter } from 'next/router'; // import CardWhitData from 'src/components/molecules/cardWhitData'; import FloatCard from 'src/components/atoms/floatCard'; const Event: NextPage = () => ( const router = useRouter() const {index} = router.query <> <FloatCard mainTitle="This is your event" description="This is your description" /> </> ) export default Event;
报错信息
Type '() => (: any, router: NextRouter | undefined, : any, { index }?: boolean) => any' is not assignable to type 'NextPage<{}, {}>'. Type '() => (: any, router: NextRouter | undefined, : any, { index }?: boolean) => any' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext<any>): {} | Promise<{}>; }'. Type '() => (: any, router: NextRouter | undefined, : any, { index }?: boolean) => any' is not assignable to type 'FunctionComponent<{}>'. Type '(: any, router: NextRouter | undefined, : any, { index }?: boolean) => any' is not assignable to type 'ReactElement<any, any>'.ts(2322)
错误原因及修复方案
核心问题
箭头函数使用圆括号()包裹函数体,但函数体内包含变量声明语句,这种写法不符合React函数组件语法规范。圆括号仅能直接返回单个表达式,无法容纳多个语句;必须改用大括号{}包裹函数体,并显式返回JSX内容。
修正后的代码
import { NextPage } from 'next'; import { useRouter } from 'next/router'; // import CardWhitData from 'src/components/molecules/cardWhitData'; import FloatCard from 'src/components/atoms/floatCard'; const Event: NextPage = () => { const router = useRouter(); const { index } = router.query; return ( <> <FloatCard mainTitle="This is your event" description="This is your description" /> </> ); }; export default Event;
额外说明
- 函数体改用大括号
{}后,必须通过return语句返回JSX结构 - 变量声明末尾建议添加分号,符合TypeScript代码规范
- 动态路由初始加载时
router.query可能为空,若需处理index为undefined的情况,可添加类型断言或可选链,例如const index = router.query.index as string;
内容的提问来源于stack exchange,提问作者ThrobbingLobbies
相关产品推荐
相关产品推荐

