Home > database >  Why this next.js and typescript page says "Property 'data' does not exist on type&quo
Why this next.js and typescript page says "Property 'data' does not exist on type&quo

Time:05-02

I am starting to use typescript with next.js

const Index: NextPage = (props) => {

  return (<p>{prop.data.name}</p>);

}
export default Index;

export const getServerSideProps = async () => {
    const data = await fetch(
        `${server}/api`
    ).then((response) => response.json());
    return {
        props: {data}
    };
};

my editor highlight the word data in {props.data.name} with this message

Property 'data' does not exist on type '{ children?: ReactNode; }'.

how can I define a type from this?

CodePudding user response:

You need to define a type and pass it to the generic param of NextPage like below

type PictureType = {
   category: string,
   createdAt: string,
   favourites: number,
   isHidden: boolean,
   title: string,
   updatedAt: string,
   url: string,
   user: string,
}
type ResponseDataType = {
   lastPictures: PictureType[],
   picturesByCat: PictureType[]
}
type PageProps = {
   data: ResponseDataType, 
}
const Index: NextPage<PageProps> = (props) => {

  return (<p>{prop.data.name}</p>);

}
export default Index;

export const getServerSideProps = async () => {
    const data = await fetch(
        `${server}/api`
    ).then((response) => response.json());
    return {
        props: {data}
    };
};
  • Related