将 Next.js 与 typescript 一起使用,但不能在 WithRouterProps 中应用泛型

ZiZ*_*eng 6 router typescript next.js

我使用 VScode 作为 IDE,给出泛型withRouter应该应用于 props.router.query 但不起作用

曾尝试创建组件接口并使用 withRouterProps 扩展,但使用 props.router.query。仍然什么都不显示


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

Run Code Online (Sandbox Code Playgroud)

泛型应该发生。即withRouterProps<{ title: string }>应该使props.router.query.title works

小智 1

您可以创建自定义类型:

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

const Component = (router: WithRouterPropsTyped<{title: string}>) => {
  return <div>Title: {router.query.title}</div>
}
Run Code Online (Sandbox Code Playgroud)