Issue
While using Next.js with TypeScript, an error occurs when attempting to return a redirect in case the data is missing.
Solution Attempted
import { GetStaticProps } from "next";
import fs from "fs/promises";
import path from "path";
function HomePage({ products }: { products: { id: string; title: string }[] }) {
return (
<ul>
{products.map((product) => {
<li key={product.id}>{product.title}</li>;
})}
</ul>
);
}
export const getStaticProps: GetStaticProps = async () => {
const filePath = path.join(process.cwd(), "data", "dummy-backend.json");
const jsonData = await fs.readFile(filePath);
const data = JSON.parse(jsonData.toString());
// THE ISSUE
if (!data) {
return {
redirect: {
destination: "/no-data",
},
};
}
if (data.products.length === 0) {
return { notFound: true };
}
return { props: { products: data.products }, revalidate: 10 };
};
export default HomePage;
Error encountered
Type '() => Promise<{ redirect: { destination: string; }; notFound?: undefined; props?: undefined; revalidate?: undefined; } | { notFound: true; redirect?: undefined; props?: undefined; revalidate?: undefined; } | { props: { ...; }; revalidate: number; redirect?: undefined; notFound?: undefined; }>' cannot be assigned to type 'GetStaticProps<{ [key: string]: any; }, ParsedUrlQuery>'.
The issue arises due to this section of code
if (!data) {
return {
redirect: {
destination: "/no-data",
},
};
}