Next.js yarn dev正常,next export时出现TypeScript类型错误
问题描述
Next.js项目在yarn dev模式下运行正常,但执行next export时抛出类型错误。
接口定义
在typings.ts中定义了如下接口:
export interface PageInformation extends SanityBody{ _type: "pageInformation"; address: string; backgroundInformation: string; email: string; role: string; heroImage: Image; title: string; phoneNumber: string; profilePic: Image; } interface SanityBody{ _createdAt: string; _id: string; _rev: string; _updatedAt: string; } interface Image{ _type: "image"; asset: { _ref: string; _type: "reference"; }; }
Hero组件代码
import Link from 'next/link' import PageInformation from "../typings"; import {urlFor} from "../sanity"; type PageInformation = typeof PageInformation; type Props = { pageInformation: PageInformation; }; // 渲染部分 <img className="relative rounded-full h-36 w-36 mx-auto object-cover" src={urlFor(pageInformation?.heroImage).url()} />
报错信息
执行next export时触发以下错误:
Type error: Property 'heroImage' does not exist on type 'typeof import("/Users/yudonglu/Desktop/Study/Web/my-portfolio/typings")'.
31 | <img
32 | className="relative rounded-full h-36 w-36 mx-auto object-cover"33 | src={urlFor(pageInformation?.heroImage).url()}
| ^
问题原因与修复方案
核心问题
你在Hero组件里做了错误的类型覆盖:
- 先从
../typings导入了PageInformation接口 - 随后用
type PageInformation = typeof PageInformation;重新定义同名类型,这里的typeof PageInformation获取的是整个typings模块的类型,而非你原本定义的接口类型,因此找不到heroImage属性。
修复步骤
删除重新定义类型的代码,直接使用导入的接口:
修改后的Hero组件代码:
import Link from 'next/link' // 注意:如果typings.ts是命名导出,改用命名导入方式 import { PageInformation } from "../typings"; import {urlFor} from "../sanity"; type Props = { pageInformation: PageInformation; };
额外说明
- 导入方式要匹配:如果
typings.ts中是export interface PageInformation(命名导出),就用import { PageInformation } from "../typings";;如果是默认导出,才用import PageInformation from "../typings";。 yarn dev模式下TypeScript类型检查较宽松,未触发报错,但next export会执行完整类型校验,因此暴露了问题。
内容的提问来源于stack exchange,提问作者Yudong Lu
相关产品推荐
相关产品推荐

