Next.js+TypeScript项目interface关键字ESLint解析错误求助
解决Next.js + TypeScript中ESLint报"Unexpected reserved word 'interface'"错误
问题重现
在Next.js结合TypeScript开发项目时,使用interface定义组件Props,触发ESLint错误:
Parsing error: Unexpected reserved word 'interface'. (3:0)eslint
相关代码、配置如下:
组件代码
import { TitleStyled, SubTitle } from "./Title.style"; interface TitleProps { titulo: String; subtitulo?: String | JSX.Element; } export default function Title(props: TitleProps) { return ( <> <TitleStyled>{props.titulo}</TitleStyled> <SubTitle>{props.subtitulo}</SubTitle> </> ); }
package.json配置
{ "name": "pets", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@emotion/react": "^11.10.5", "@emotion/styled": "^11.10.5", "@mui/material": "^5.11.4", "@next/font": "13.1.1", "@types/node": "18.11.18", "@types/react": "18.0.26", "@types/react-dom": "18.0.10", "eslint": "8.31.0", "eslint-config-next": "13.1.1", "next": "13.1.1", "react": "18.2.0", "react-dom": "18.2.0", "typescript": "4.9.4" } }
tsconfig.json配置
{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "exclude": ["node_modules"] }
问题原因
核心问题是文件扩展名不匹配:你在代码中使用了TypeScript专属语法(interface、类型注解props: TitleProps),但文件后缀是.js。ESLint会默认把.js文件当作纯JavaScript处理,而interface是TypeScript的保留字,在JavaScript中属于非法语法,因此抛出解析错误。
解决步骤
修改文件扩展名
将组件文件的后缀从.js改为.tsx(因为是React组件,需要支持JSX语法,所以用.tsx而非.ts)。确认tsconfig.json配置
检查你的tsconfig.json中include字段是否包含**/*.tsx,确保TypeScript编译器能识别该文件。你的配置中已经包含,这一步无需修改。可选:代码优化
代码中的String(大写)是JavaScript的包装对象类型,TypeScript中推荐使用小写的string表示原始字符串类型,修改后更符合TS规范:interface TitleProps { titulo: string; subtitulo?: string | JSX.Element; }
验证
修改完成后,重启ESLint服务或运行npm run lint,错误应该会消失。
内容的提问来源于stack exchange,提问作者dlima
相关产品推荐
相关产品推荐

