How to make TypeScript happy with params on getStaticProps
Answered
Chartreux posted this in #help-forum
ChartreuxOP
Hey guys how can I make TypeScript happy with this code? I want to type the params and getStaticProps on my [slug].tsx file. Heres the code:
export async function getStaticProps({ params }) {
const slug = params.slug;
const prisma = new PrismaClient();
const cat = await prisma.cat.findFirst({
where: {
slug,
},
});
if (!cat) {
throw new Error(`Couldnt find cat with slug: ${params.slug}`);
}
const images = JSON.parse(cat.images) as CatImageType[];
return {
props: {
cat,
images,
},
};
}Answered by joulev
type Params = { slug: string };
type Props = { name: string };
export const getStaticProps: GetStaticProps<Props, Params> = ({ params }) => {
console.log(params?.slug);
return { props: { name: "hello world" }}
}11 Replies
@Chartreux Hey guys how can I make TypeScript happy with this code? I want to type the params and getStaticProps on my [slug].tsx file. Heres the code:
tsx
export async function getStaticProps({ params }) {
const slug = params.slug;
const prisma = new PrismaClient();
const cat = await prisma.cat.findFirst({
where: {
slug,
},
});
if (!cat) {
throw new Error(`Couldnt find cat with slug: ${params.slug}`);
}
const images = JSON.parse(cat.images) as CatImageType[];
return {
props: {
cat,
images,
},
};
}
have a look at these types
import {
GetStaticProps,
GetStaticPropsContext,
GetStaticPropsResult
} from "next";ChartreuxOP
i did see them
didnt get them to work however
but i need to use the context one for the params right?
type Params = { slug: string };
type Props = { name: string };
export const getStaticProps: GetStaticProps<Props, Params> = ({ params }) => {
console.log(params?.slug);
return { props: { name: "hello world" }}
}Answer
type Params = { slug: string };
type Props = { name: string };
export function getStaticProps({ params }: GetStaticPropsContext<Params>): GetStaticPropsResult<Props> {
console.log(params?.slug);
return { props: { name: "hello world" }}
}ChartreuxOP
alright thanks
guess i need to read up on what does #Unknown Channel thingies mean
what are they called btw?