javascript 类型“(新值:DateRange< dateFns>)=>void'不能赋值给类型'(日期:日期范围< unknown>,键盘输入值?:弦|未定义)=>无效'

c3frrgcw  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(137)

我使用的是MUI日期范围选择器(https://mui.com/x/react-date-pickers/date-range-picker/),结果如下:

<StaticDateRangePickerStyled
            displayStaticWrapperAs="desktop"
            value={value}
            onChange={handleDatePickerChange}
            renderDay={(
              date,
              dateRangePickerDayProps: DateRangePickerDayProps<dateFns>
            ) => <DateRangePickerDayStyled {...dateRangePickerDayProps} />}
            dayOfWeekFormatter={(day: string) => dayOfWeek[day]}
            components={{
              LeftArrowButton: ({ onClick }) => (
                <IconButton
                  size="md"
                  Icon={ArrowBackStyled}
                  onClick={onClick}
                />
              ),
              RightArrowButton: ({ onClick }) => (
                <IconButton
                  size="md"
                  Icon={ArrowForwardStyled}
                  onClick={onClick}
                />
              ),
            }}
          />

我的联络人是

const handleDatePickerChange = useCallback((newValue: DateRange<dateFns>) => {
    setValue(newValue)
  }, [])

但TypeScript却在抱怨:

Type '(newValue: DateRange<dateFns>) => void' is not assignable to type '(date: DateRange<unknown>, keyboardInputValue?: string | undefined) => void'.

我哪里做错了?

rqqzpn5f

rqqzpn5f1#

出现此错误的原因是,StaticDateRangePickerStyled组件中onChange函数的返回类型小于(newValue:DateRange)=〉void,而预期类型为(date:日期范围,键盘输入值?:弦|未定义)=〉空。
一种可能的解决方案是显式地将onChange的类型设置为(date:日期范围,键盘输入值?:弦|undefined)=〉void在重写时让TypeScript自动推断类型,如下所示:

<StaticDateRangePickerStyled
  onChange={handleDatePickerChange as (date: DateRange<unknown>, keyboardInputValue?: string | undefined) => void}
/>

相关问题