>
テストのためにコードの途中でreturnしたりredirectさせたい時があります。returnやredirectの後のコードでエラーが発生することがあります。returnなどの後のコードは到達不能なため、TypeScriptはnullチェックしません。これが原因でエラーが発生します。
export default async function Page() {
return; // テストのために記述。
const post: Post | null = await getPost();
if (!post) throw new Error("post is null");
const postId: string = post.id; // Error: 'post' is possibly 'null'.
// ...
}
下記のようにif文を使うと、エラーが発生しなくなります。
export default async function Page() {
if (1 === 1) return; // テストのために記述。
const post: Post | null = await getPost();
if (!post) throw new Error("post is null");
const postId: string = post.id; // エラーが発生しない。
// ...
}