我有接口FormData,它应该与onFinish函数接收的值类型相同,但是当我将
const onFinish = (values: FormData) => {
我得到错误**类型'(值:FormData)=〉void'不可赋值给类型'(values:unknown)=〉void'.**我尝试过伪造数据,并在提交表单时创建与onFinish函数相同的对象:
interface FormData {
firstName: string;
lastName: string;
username: string;
password: string;
confirmPassword: string;
}
const obj: FormData = {
firstName: 'andrija',
lastName: 'gajic',
username: 'radojica51',
password: 'idegas51',
confirmPassword: 'idegas51'
}
当这样做时,它不会抛出任何错误,尽管它与表单接收的数据相同
import axios from 'axios';
import { Form, FormCaption } from './Form.style';
import { Input, Button } from 'antd';
interface FormData {
firstName: string;
lastName: string;
username: string;
password: string;
confirmPassword: string;
}
const FormComponent = () => {
// change values type to FormData
const onFinish = (values: any) => {
if (values.password !== values.confirmPassword) {
message.error('Passwords don\'t match!');
return;
}
console.log(values);
axios.post('http://localhost:5000/register', values);
}
return (
<Form onFinish={onFinish}>
<FormCaption>Register</FormCaption>
<FormElement.Item
label="First name"
name="firstName"
rules={[
{
required: true,
message: 'Please enter your first name!',
},
]}
>
<Input />
</FormElement.Item>
<FormElement.Item
label="Last name"
name="lastName"
rules={[
{
required: true,
message: 'Please enter your last name!',
},
]}
>
<Input />
</FormElement.Item>
<FormElement.Item
label="Username"
name="username"
rules={[
{
required: true,
message: 'Please enter the username!',
},
{
min: 6,
max: 20,
message: 'Must be between 6 and 20 characters'
}
]}
>
<Input />
</FormElement.Item>
<FormElement.Item
label="Password"
name="password"
rules={[
{
required: true,
message: 'Please enter the password!',
},
{
min: 6,
max: 20,
message: 'Must be between 6 and 20 characters'
}
]}
>
<Input.Password />
</FormElement.Item>
<FormElement.Item
label="Confirm Password"
name="confirmPassword"
rules={[
{
required: true,
message: 'Please confirm your password!',
},
{
min: 6,
max: 20,
message: 'Must be between 6 and 20 characters'
}
]}
>
<Input.Password />
</FormElement.Item>
<Button htmlType="submit">Register</Button>
</Form>
)
}
export default FormComponent;
2条答案
按热度按时间wsewodh21#
我个人不喜欢这样写
jsx
,但你可以这样传递期望的表单类型:现在
onFinish
将不会抱怨,并有正确的类型。Sourceztmd8pv52#
你可以用下面的代码来处理
并在下面的onFinish中使用
Lern more about as keyword这里