reactjstypescriptmaterial-uidatepickerdayjs

How to resolve TypeScript error "Type 'Dayjs' is missing properties from type 'Date'" when using Day.js with Material-UI DatePicker?


I'm trying to use Day.js with Material-UI's DatePicker component in my React project. However, when I set the minDate and maxDate properties to Day.js objects, I get a TypeScript error:

Type 'Dayjs' is missing the following properties from type 'Date': toDateString, toTimeString, toLocaleDateString, toLocaleTimeString, and 35 more.

I understand that DatePicker expects minDate and maxDate to be of type Date, but Day.js returns a Dayjs object.

Code:

import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";

interface DatepickerProperties {
  label: string;
  onChange: (value: Date | null) => void;
  disablePast?: boolean;
}

function Datepicker({
  label,
  onChange,
  disablePast = false,
}: DatepickerProperties) {
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DatePicker
        disablePast={disablePast}
        label={label}
        onChange={onChange}
        minDate={dayjs()}
        maxDate={dayjs("9999-12-31")}
      />
    </LocalizationProvider>
  );
  );
}

Expected Behavior: I expect the DatePicker component to accept minDate and maxDate as Day.js objects without any TypeScript errors.

Actual Behavior: I'm getting the TypeScript error mentioned above when using Day.js objects for minDate and maxDate.

What I've tried: I've attempted to convert the Day.js object to a Date object using toDate(), but this cause a bunch of another errors:

AdapterDayjs.js:384 Uncaught TypeError: value.isAfter is not a function
    at AdapterDayjs.isAfterDay (AdapterDayjs.js:384:22)
    at getDefaultReferenceDate (getDefaultReferenceDate.js:53:38)
    at Object.getInitialReferenceValue (valueManagers.js:21:12)
    at useFieldState.js:58:41
    at mountState (react-dom.development.js:16986:20)
    at Object.useState (react-dom.development.js:17699:16)
    at Object.useState (react.development.js:1622:21)
    at useFieldState (useFieldState.js:48:35)
    at useField (useField.js:29:7)
    at useDateField (useDateField.js:29:10)

How can I properly resolve the TypeScript error(s)?


Solution

  • Your code looks good, but I think you are passing the DatepickerProperties interface incorrectly.

    If you want to use Dayjs objects for date manipulation, you should change the type of the onChange callback from Date to Dayjs. This way, you can avoid converting between Date and Dayjs objects and keep your code consistent.

    For example, you can try this:

    import dayjs, { Dayjs } from "dayjs";
    
    interface DatepickerProperties {
      label: string;
      onChange: (value: Dayjs | null) => void;
      disablePast?: boolean;
    }
    

    You can see the whole example here.