首页 > 解决方案 > 如何在不出现 Typescript 错误的情况下将 signUpConfig 传递给 Amplify 的 withAuthenticator HOC

问题描述

我正在尝试使用 Typescript 和 AWS Amplify 创建一个反应应用程序以进行用户身份验证。我想将注册字段限制为电子邮件和密码。

根据AWS doc,我应该能够使用下面提供的最小示例来实现这一点,但是

TypeScript error in ......../frontend/src/App.tsx(43,41):
Argument of type '{ signUpConfig: { header: string; hideAllDefaults: boolean; signUpFields: { label: string; key: string; required: boolean; displayOrder: number; type: string; }[]; }; }' is not assignable to parameter of type 'AmplifyAuthenticator & HTMLAttributes<HTMLAmplifyAuthenticatorElement> & ReactProps & RefAttributes<...>'.
  Object literal may only specify known properties, and 'signUpConfig' does not exist in type 'AmplifyAuthenticator & HTMLAttributes<HTMLAmplifyAuthenticatorElement> & ReactProps & RefAttributes<...>'.  TS2345

    41 |   };
    42 | 
  > 43 | export default withAuthenticator(App, { signUpConfig });
       |                                         ^
    44 |

最小的例子

import './App.css';
import React from 'react';
import awsConfig from './amplify-config';

import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react';
import Amplify from 'aws-amplify';

Amplify.configure(awsConfig);

function App() {
  return (
    <div className="App">
        
    <AmplifySignOut />
      <header className="App-header">
        Test
      </header>
    </div>
  );
}

const signUpConfig = {
    header: 'My Customized Sign Up',
    hideAllDefaults: true,
    signUpFields: [
      {
        label: 'My custom email label',
        key: 'email',
        required: true,
        displayOrder: 1,
        type: 'string'
      },
      {
        label: 'My custom email label',
        key: 'password',
        required: true,
        displayOrder: 2,
        type: 'password'
      }
    ]
  };

export default withAuthenticator(App, { signUpConfig });

我试图弄清楚 signUpConfig 的打字稿类型是什么。我认为是这样ComponentPropsWithRef<typeof AmplifyAuthenticator>,但这并不能真正帮助我了解将什么放入 signUpConfig 对象或为什么它不起作用。根据错误消息,类型是'AmplifyAuthenticator & HTMLAttributes<HTMLAmplifyAuthenticatorElement> & ReactProps & RefAttributes<...>',但这也对我没有帮助。

如果我没有传入signUpConfig,那么该应用程序将按预期工作。

如果我在signUpConfig没有将其包裹的情况下通过{},那么我会收到此错误。

Type '{ header: string; hideAllDefaults: boolean; signUpFields: { label: string; key: string; required: boolean; displayOrder: number; type: string; }[]; }' has no properties in common with type 'AmplifyAuthenticator & HTMLAttributes<HTMLAmplifyAuthenticatorElement> & ReactProps & RefAttributes<...>'.

标签: reactjstypescriptaws-amplifyaws-amplify-sdk-js

解决方案


最新版本(今天是 2021 年 4 月 21 日)@aws-amplify/ui-react库现在基于插槽,并且需要稍微不同的配置方法。对我有用的是放大文档中的这个例子:https ://docs.amplify.aws/ui/auth/authenticator/q/framework/react#customization


推荐阅读