在 TypeScript 的 Next.js 中创建 HOC withAuth 的最佳方法是什么?

在 TypeScript 的 Next.js 中创建 HOC withAuth 的最佳方法是什么?

问题:

我有一个 Next.js 应用程序,并且正在使用next-authpackage.json。我正在尝试创建一个 HOC 来包裹实际组件并确定它是否有会话。我也在使用 eslint。这是我的代码:

import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';

type Props = any;

const withAuth = (Component: React.ComponentType<Props>) => {
  const Auth = (props: Props) => {
    const router = useRouter();
    const { status } = useSession({
      required: true,
      onUnauthenticated() {
        router.push('/welcome/login');
      },
    });

    if (status === 'loading') {
      return 'Loading ...';
    }

    return <Component {...props} />;
  };
  return Auth;
};

export default withAuth;

Eslint 向我发出有关我使用 type 的警告any我尝试将这两行更改为使用通用类型的位置:

const withAuth = <P extends {}>(Component: React.ComponentType<P>) => {
    const Auth = (props: P) => {

但现在它报错了:

Error: Don't use `{}` as a type. `{}` actually means "any non-nullish value".
- If you want a type meaning "any object", you probably want `object` instead.
- If you want a type meaning "any value", you probably want `unknown` instead.
- If you want a type meaning "empty object", you probably want `Record<string, never>` instead.
- If you really want a type meaning "any non-nullish value", you probably want `NonNullable<unknown>` instead.  @typescript-eslint/ban-types

当我们必须将组件作为 props 传递时,编写 HOC 的最佳方法是什么?我不知道它会是什么样的组件

解决方案或解答

一般来说,TypeScript 建议不要使用{}作为泛型类型约束,因为它不会施加任何类型检查约束,因此它本质上与使用 一样宽松any。

您可以使用unknownorRecord<string, unknown>来获得更好的类型安全性,并且 ESLint 错误也不会弹出。

这些类型基本上假设您不知道该对象将采用什么形状,但它不会是nullor undefined,使其足够灵活以包装任何组件。

所以在你的情况下:

const withAuth = <P extends Record<string, unknown>>(
  Component: React.ComponentType<P>
): React.FC<P> => {
  const Auth: React.FC<P> = (props) => {
    const router = useRouter();
    const { status } = useSession({
      required: true,
      onUnauthenticated() {
        router.push('/welcome/login');
      },
    });

    if (status === 'loading') {
      return 'Loading ...';
    }

    return <Component {...props} />;
  };

  return Auth;
};

export default withAuth;

所以在这里, props 参数的类型不是 ,any而是 类型P,这是我们限制为 的泛型类型Record<string, unknown>。文章来源地址https://www.toymoban.com/article/381.html

到此这篇关于在 TypeScript 的 Next.js 中创建 HOC withAuth 的最佳方法是什么?的文章就介绍到这了,更多相关内容可以在右上角搜索或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

原文地址:https://www.toymoban.com/article/381.html

如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

    系统发生错误

    系统发生错误

    您可以选择 [ 重试 ] [ 返回 ] 或者 [ 回到首页 ]

    [ 错误信息 ]

    页面错误!请稍后再试~

    Tob