本地运行正常,部署至Vercel时出现TypeScript类型报错求助
解决Vercel部署时的TypeScript类型错误
问题根源
你已经定义了Image接口,但未正确将类型关联到组件Props和数组元素,导致TypeScript无法识别images数组元素的结构。本地开发可能启用了宽松类型检查,而Vercel部署时会严格执行类型规则,因此触发报错。
修复步骤
1. 明确组件Props类型
将组件的props从any改为包含Image数组的明确类型:
interface Image { imageUrl: string; // 替换any为具体类型,比如string alt: string; } interface GalleryBlockProps { images: Image[]; } export default function GalleryBlock({ images }: GalleryBlockProps) { // ... 原有逻辑代码 }
2. 修正map循环的元素类型
所有images.map的地方,将image: {}改为image: Image,示例:
// 主图区域的map {images.map((image: Image, index: number) => index === 0 ? ( "" ) : ( <img key={index} className="absolute inset-x-1/2 transform -translate-x-1/2 inset-y-1/2 -translate-y-1/2 max-h-full max-w-full transition-opacity duration-1000" style={{ opacity: "0" }} id={`image-${index}`} src={image.imageUrl} alt={image.alt} /> ) )}
同理,下方两个缩略图区域的map也要修改元素类型:
// 左侧缩略图map {(currentIndex > 1 ? images.slice(currentIndex - 2, currentIndex) : images .slice(images.length - 2 + currentIndex) .concat(images.slice(0, currentIndex)) ).map((image: Image, index: number) => currentIndex === images.indexOf(image) ? ( "" ) : ( <img key={index} className="max-h-full mx-[5px] cursor-pointer" onClick={() => changeToImage(images.indexOf(image))} src={image.imageUrl} alt={image.alt} /> ) )}
3. 优化索引判断的稳定性(可选)
images.indexOf(image)依赖对象引用比较,若images是从Sanity获取的动态数据,可能出现索引判断错误。建议给Image接口添加唯一ID字段,改用ID匹配:
interface Image { id: string; // 添加Sanity返回的唯一ID imageUrl: string; alt: string; } // 修改缩略图的点击和判断逻辑 onClick={() => changeToImage(images.findIndex(img => img.id === image.id))} // ... currentIndex === images.findIndex(img => img.id === image.id) ? ( "" ) : ( // ... )
内容的提问来源于stack exchange,提问作者Rishi Patel
相关产品推荐
相关产品推荐

