🔷

never型と推論されたことによるTypeScriptの型エラー

に公開

はじめに

Vercelへのデプロイ時にエラーが発生したので原因と対処法についてまとめます。

問題

VercelにNext.jsのプロジェクトをデプロイしたところ、以下のようなエラーがログに表示されました。

[20:37:35.476] Running build in Washington, D.C., USA (East) – iad1
[20:37:35.493] Cloning github.com/Juna1013/mdl-welcome-site (Branch: main, Commit: da2307b)
[20:37:36.216] Cloning completed: 723.000ms
[20:37:37.578] Restored build cache from previous deployment
[20:37:38.090] Running "vercel build"
[20:37:38.449] Vercel CLI 41.6.2
[20:37:38.696] Error while parsing config file: "/vercel/path0/package-lock.json"
[20:37:38.704] Error while parsing config file: "/vercel/path0/package-lock.json"
[20:37:38.714] Error while parsing config file: "/vercel/path0/package-lock.json"
[20:37:38.715] Installing dependencies...
[20:37:40.014] 
[20:37:40.015] up to date in 1s
[20:37:40.015] 
[20:37:40.016] 138 packages are looking for funding
[20:37:40.016]   run npm fund for details
[20:37:40.047] Detected Next.js version: 15.2.3
[20:37:40.052] Running "npm run build"
[20:37:40.161] 
[20:37:40.162] > my-project@0.1.0 build
[20:37:40.162] > next build
[20:37:40.162] 
[20:37:40.925]  ⚠ Found lockfile missing swc dependencies, run next locally to automatically patch
[20:37:41.095]    ▲ Next.js 15.2.3
[20:37:41.096] 
[20:37:41.118]    Creating an optimized production build ...
[20:37:41.704]  ⚠ Found lockfile missing swc dependencies, run next locally to automatically patch
[20:37:43.811]  ⚠ Found lockfile missing swc dependencies, run next locally to automatically patch
[20:37:44.727]  ⚠ Found lockfile missing swc dependencies, run next locally to automatically patch

原因・解決方法

TypeScriptの型エラーでした。useRefの型定義が不適切だとエラーメッセージに表示されていました。aboutRefactivitiesRefの初期値がnullで、TypeScriptがこれをnever型と推論したため、scrollIntoViewメソッドが存在しないというエラーが発生していました。

このエラーを修正するために、useRefに正しい型注釈を追加する必要があります。

修正前

const aboutRef = useRef(null);
const activitiesRef = useRef(null);

修正後

const aboutRef = useRef<HTMLDivElement | null>(null);
const activitiesRef = useRef<HTMLDivElement | null>(null);

おわりに

この修正により、TypeScriptはプロパティのメソッドを正しく認識できるようになり、型エラーが解消されました。

Discussion