Correct way to type generic of DatePickerProps from DatePicker from mui-x

72 Views Asked by At

I have the following component and had set Localization like the following

function CustomDatePicker(props: DatePickerProps<unknown> & React.RefAttributes<HTMLDivElement>) {
  return (
    <StyledDatePicker
      disableHighlightToday
      format={DEFAULT_DATE_FORMAT}
      slots={{
        openPickerIcon: IconCalendar,
      }}
      {...props}
    />
  );
}

LocalizationProvider using AdapterDateFns

<LocalizationProvider
      dateAdapter={AdapterDateFns}
      adapterLocale={en}
> ....

I have it taking in props, what should i set the generic of DatePickerProps<??>

Having the generic set to unknownseem to work for now, but onChange'svalue is typed as unknown.

<CustomDatePicker
  onChange={(value) => { //typeof value === unknown
....

now i have to type assert the value when using on a callback

onChange={value => onChangeDate(value as Date | null)}
1

There are 1 best solutions below

0
qud On

The Generic seems to be what your adapter returns, in my case built in Date because I am using date-fns adapters. So if your using moment/dayjs, you set the generic as the corresponding object type.

Setting the generic will type the onChange and value props as a result