如何修复 Typescript 中的“Type '{}' is missing in the following properties...”错误?

Jer*_*L30 11 types typescript reactjs antd

我是 Typescript 的新手,因此遇到了问题。我正在使用 Ant Design 并遵循如何在 Typescript 中使用 Form 但使用FunctionComponent; 但是,我收到了 Typescript 抛出的错误:

TypeScript error: Type '{}' is missing the following properties from type 'Readonly<RcBaseFormProps & Pick<SetupFormProps, "username" | "email" | "password" | "confirm_password" | "first_name" | "last_name">>': username, email, password, confirm_password, and 2 more. TS2740

这是代码:

import React, { useState } from 'react';
import { Form, Input, Row, Col } from 'antd';
import { FormComponentProps } from 'antd/lib/form';


interface SetupFormProps extends FormComponentProps {
  username: string;
  email: string;
  password: string;
  confirm_password: string;
  first_name: string;
  last_name: string;
}

const SetupForm: React.FC<SetupFormProps> = ({ form }) => {
  ...
  return (
    <Form id="setup-form" layout="vertical" onSubmit={handleSubmit}>...</Form>
  )
}

export default Form.create<SetupFormProps>({ name: 'register' })(SetupForm);
Run Code Online (Sandbox Code Playgroud)

在我的另一个组件中,我以这种方式访问​​它:

import SetupForm from './form';

<SetupForm />
Run Code Online (Sandbox Code Playgroud)

Bsa*_*lex 13

你的 props 界面中的所有 props 都是必需的(它们不能是未定义的)

interface SetupFormProps extends FormComponentProps {
  username: string;
  email: string;
  password: string;
  confirm_password: string;
  first_name: string;
  last_name: string;
}
Run Code Online (Sandbox Code Playgroud)

但是您正在使用您的组件而没有从界面中指定道具

<SetupForm />
Run Code Online (Sandbox Code Playgroud)

所以你应该从界面中指定道具(SetupFormProps)

<SetupForm username="myUserName" ...etc />
Run Code Online (Sandbox Code Playgroud)

或者让道具可选

interface SetupFormProps extends FormComponentProps {
  username?: string;
  email?: string;
  password?: string;
  confirm_password?: string;
  first_name?: string;
  last_name?: string;
}
Run Code Online (Sandbox Code Playgroud)