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.