ZiZi Zheng
ZiZi Zheng

Reputation: 71

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

Upvotes: 6

Views: 1316

Answers (1)

AidanCQ
AidanCQ

Reputation: 11

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>
}

Upvotes: 1

Related Questions