Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Next.js with typescript but can not apply generic in WithRouterProps

I'm using VScode as IDE, giving generic to withRouter should be applied on props.router.query but not working

Have tried to create component interface and extends with withRouterProps, but props.router.query. still show nothing


    import { withRouter, WithRouterProps } from 'next/router';
    import Layout from '../components/Layout';
    import React from 'react';

    class Page extends React.Component<IPageProps> {
        render() {
            console.log(this.props.router.query.);  <=== should show title in intellience but nothing happened 
            return (
                <Layout>
                    {/* <h1>{this.props}</h1> */}
                    <p>This is the blog post content.</p>
                </Layout>
            );
        }
    }

    export default withRouter(Page);

    interface IPageProps extends WithRouterProps<{ title: string }> {
        test: string;
    }

The generic should take place. i.e. withRouterProps<{ title: string }> should make props.router.query.title works

like image 823
ZiZi Zheng Avatar asked Jan 11 '19 07:01

ZiZi Zheng


People also ask

Can next js be used with TypeScript?

Next.js provides an integrated TypeScript experience, including zero-configuration set up and built-in types for Pages, APIs, and more.

What is NextPage in NextJS?

NextPage is a type exported by NextJS. When we write Page: NextPage we're saying that our Page component is of type NextPage . Follow this answer to receive notifications.


1 Answers

You can create a custom type:

type WithRouterPropsTyped<Query extends WithRouterProps["router"]["query"]> = WithRouterProps & {
  query: Query
}

const Component = (router: WithRouterPropsTyped<{title: string}>) => {
  return <div>Title: {router.query.title}</div>
}
like image 173
AidanCQ Avatar answered Oct 05 '22 22:10

AidanCQ