You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS+Formik+Yup开发遇TypeScript错误,求解决方案

解决Next.js + Formik + Yup表单的TypeScript错误

错误原因及修复步骤

1. 变量'Myform'隐式拥有'any'类型

问题根源:组件的箭头函数声明语法错误,const Myform () => {不符合语法规范,导致TypeScript无法推断组件类型。
修复:修正为正确的箭头函数写法,可选显式指定React组件类型:

// 错误写法
const Myform () => {

// 正确写法(二选一)
const Myform: React.FC = () => {
// 或省略显式类型,TypeScript自动推断
const Myform = () => {

2. 类型'string | FormikErrors'无法分配给类型'ReactNode'

问题根源:调用useFormik时未传入泛型参数,TypeScript无法准确推断formik.errors的字段类型,默认每个字段错误类型为string | FormikErrors<any>,与React的ReactNode类型不兼容。
修复:给useFormik传入定义好的Values泛型,明确每个字段的错误类型为string | undefined:

const formik = useFormik<Values>({
  initialValues: initValues,
  validationSchema: advanceSchema,
  onSubmit: async (values, actions) => {
    await new Promise((resolve) => setTimeout(resolve, 1000))
    actions.resetForm();      
  }
})

额外代码优化点

  • 类型定义中,将大写Boolean改为小写boolean(TypeScript原始类型规范);
  • 修复input标签语法错误:type='date '{...}中多余的空格,改为type='date' {...};
  • 表单绑定onSubmit={formik.handleSubmit},否则提交按钮无法触发Formik的提交逻辑;

修正后的完整代码

"use client"

import { useFormik } from 'formik';
import * as Yup from 'yup';
import type React from 'react';

type Values = {
    date: Date;
    checkbox1: boolean;
    radio1: boolean;
}

const Myform: React.FC = () => {
    const initValues: Values = {
        date: new Date(),
        checkbox1: false, 
        radio1: false,
    }

    const advanceSchema = Yup.object().shape({
        checkbox1: Yup.boolean()
            .required("You must accept our terms and conditions!")
            .oneOf([true], "You must accept our terms and conditions!"),           

        radio1: Yup.boolean()
            .required("Select Radio1")
            .oneOf([true], "Select payment Radio1."),     
        
        date: Yup.date()
            .min(new Date(), "Please Select Correct Date")
            .required("Select your preferred date"),                      
    })

    const formik = useFormik<Values>({
        initialValues: initValues,
        validationSchema: advanceSchema,
        onSubmit: async (values, actions) => {
            await new Promise((resolve) => setTimeout(resolve, 1000))
            actions.resetForm();      
        }
    })

    return (
        <form onSubmit={formik.handleSubmit}>   
            <label htmlFor='date'>
                {formik.errors.date && formik.touched.date 
                    ? formik.errors.date 
                    : "Select your preferred date"}
            </label>          
            <input 
                type='date' 
                {...formik.getFieldProps("date")} 
                placeholder='Select your preferred date'
            />
            <p>Select Radio1</p>
            <input type="radio" {...formik.getFieldProps("radio1")} />
            <label htmlFor="radio1">
                {formik.errors.radio1 && formik.touched.radio1 && !formik.values.radio1
                    ? formik.errors.radio1 
                    : ""} 
            </label>    

            <input type="checkbox" {...formik.getFieldProps("checkbox1")}/>  

            <p> I have read and agree to the Terms and Conditions</p>                          

            <p>  
                {formik.errors.checkbox1 && formik.touched.checkbox1 
                    ? formik.errors.checkbox1 
                    : ""} 
            </p>

            <button 
                type="submit" 
                className={`${formik.isSubmitting ? 'bg-slate-400' : ""}`}
                disabled={formik.isSubmitting}
            > 
                Submit
            </button>
        </form>
    )
}

export default Myform

内容的提问来源于stack exchange,提问作者2div

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 21:20:33