Next.js中TypeScript报错:'Options'与'NavigateOptions'类型不兼容
我编写了以下代码:
import { useRouter } from 'next/navigation'; interface Options { scroll: boolean; } const Component = () => { const router = useRouter(); const updateSearchParams = () => { const searchParams = new URLSearchParams(window.location.search); const newPathname = `${window.location.pathname}?${searchParams.toString()}`; const options: Options = { scroll: false }; router.push(newPathname, options); }; return ( ); }; export default Component;
运行时遇到TypeScript类型不兼容错误:我自定义了Options类型,但router.push期望接收NavigateOptions类型,导致类型不匹配。
直接传递参数的写法同样报错:
router.push(newPathname, { scroll: false });
错误提示如下:
Argument of type '{ scroll: boolean; }' is not assignable to parameter
of type 'NavigateOptions'. Object literal may only specify known
properties, and 'scroll' does not exist in type 'NavigateOptions'.
这是Next.js的问题还是我代码的问题?
我的项目package.json配置如下:
{ "name": "nex-js", "version": "1.2.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "export": "next export", "lint": "eslint --fix \"src/**/*.{js,jsx,ts,tsx}\"", "format": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\"", "build:icons": "tsc -b src/iconify-bundle && node src/iconify-bundle/bundle-icons-react.js" }, "dependencies": { "@headlessui/react": "^1.7.14", "@types/node": "20.2.1", "@types/react": "18.2.6", "@types/react-dom": "18.2.4", "autoprefixer": "10.4.14", "next": "13.4.12", "postcss": "8.4.23", "react": "18.2.0", "react-dom": "18.2.0", "tailwindcss": "3.3.2", "typescript": "5.0.4" }, "devDependencies": { "@types/node": "20.2.1", "@types/react": "18.2.6", "@typescript-eslint/eslint-plugin": "5.55.0", "@typescript-eslint/parser": "5.55.0", "eslint": "8.36.0", "eslint-config-next": "13.3.2", "eslint-config-prettier": "8.7.0", "eslint-import-resolver-alias": "1.1.2", "eslint-import-resolver-typescript": "3.5.3", "eslint-plugin-import": "2.27.5", "prettier": "2.8.4", "typescript": "5.0.4" }, "resolutions": { "@emotion/react/@emotion/babel-plugin/@babel/core": "7.21.5", "@emotion/react/@emotion/babel-plugin/@babel/plugin-syntax-jsx/@babel/core": "7.21.5" } }
我无意中解决了问题:查看node_modules里的类型定义,发现确实存在scroll相关类型,之后错误就消失了,但我不清楚具体原因。
问题分析与正确解决方式
版本不匹配导致类型差异:你的
eslint-config-next版本是13.3.2,但Next.js本体版本是13.4.12,两者版本不一致会导致类型定义不同步。13.4.x版本的NavigateOptions已经包含scroll参数,但旧版eslint配置对应的类型定义尚未更新。TypeScript缓存问题:TypeScript会缓存类型定义文件,当你查看node_modules时,可能触发了IDE重新读取类型文件,或者缓存自动更新,此时正确的
NavigateOptions类型被识别,错误自然消失。正确解决步骤:
- 将
eslint-config-next版本升级到与Next.js一致的13.4.12,避免版本不兼容带来的类型问题。 - 清除TypeScript缓存:运行
npx tsc --clearCache,或重启IDE让其重新加载类型定义。 - 无需自定义
Options类型,直接从next/navigation导入官方的NavigateOptions类型使用:import { useRouter, NavigateOptions } from 'next/navigation'; // ... const options: NavigateOptions = { scroll: false }; router.push(newPathname, options);
- 将
内容的提问来源于stack exchange,提问作者Frank HAWK

