How to destructure objects with typescript in next js.

Hello, in this post I am going to be showing you how you can destructue objects with types in a function or const component in next.js.
So I was building a contactList web app using next.js, prisma, typescript and a simple sqlite database and I needed to destructure some data returned from the prisma backend by get serverside props. and it kept showing this error "Binding element 'initialContact' implicitly has an 'any' type".
I tried setting a type to the object as I normally do to others like so "{initialContact:any}" but that did not solve the issue. So after a couple of minutes searching the web I discovered a fix on flaviocopes website which i'll be sharing with you.

Let's say initialContacts is the data being returned by getServerSideProps as shown below;

export async function getServerSideProps() {

    const contacts: Contact[] = await prisma.contact.findMany();
    return {
        props: {
            initialContact: contacts

        }
    }
}

Then to destructure it and use it in your component ( class or functional) you just destructure it within the braces and declare a type as shown below;

function Crud({ initialContact }: { initialContact: any }) {

 return(
    <>
    </>
 )
}

Conclusion

Following the method above will enable you to destructure data returned by getServerSideProps when using typescript in a next js component. As always thanks for reading, if you have any questions about the post feel free to leave a comment down below.

Author
author-image

Hello, my name is Abubakar Zakari. Am a budding fullstack developer from Nigeria who loves developing softwares and learning new frameworks and langauges.

Comment

Select image


Comments
No comment yet

DEVMAESTERS

Newsletter

Services

Frontend Development |Backend Development |Full Website Development |Bootstrap Website upgrades | Website Debbugging | Website Hosting & deployment

Contact

Interested in hiring me or collaborating with me on a project, click on any of the links below to get my social media handle

Or contact me via Tel: (+234)-806-225-7480 | Email: abubakarzakari1703@gmail.com

Copywright@devmaesters.com
Privacy Policy

By using our website,
you agree that devmaesters can store cookies on your device and disclose information in accordance with our privacy policy.