reactjstypescriptmaterial-uidatepickerdayjs

How to use Material UI date picker with typescript?


Look, Im not one to just put 'any' as the type when i dont know what to do, but i must say, i am seriously getting frustrated here. I am using Material UI date picker along side the DayJS date library.

This is the example material UI have on their website:

enter image description here

On the example above, they are clearly using the Dayjs type which dayjs provides, which is also what i use in my function below:

const BookingComponent = () => {
    const [selectedDate, setSelectedDate] = useState<Dayjs | null>(null)
    return (
        <div className='flex justify-center'>
            <Stack spacing={4} sx={{ width: '280px' }}>
            <DatePicker
                label='Select a Date'
                format='DD-MM-YYYY'
                value={selectedDate}
                onChange={newValue => {setSelectedDate(newValue)}}    
            />
            <button onClick={() => console.log(selectedDate)}>click</button>
            </Stack>
        </div>
    )
}

export default BookingComponent

When i log 'selectedDate' out into the console, this is what it looks like:

enter image description here

As you can see from the picture above, '$d' is holding the date information that i need. So i try to console it out by typing 'console.log(selectedDate.$d)' but then i get this error:

Property '$d' does not exist on type 'Dayjs'

So i actually do not understand, I obviously dont just want to put 'any' as the type and move on but if it doesnt exist on type 'Dayjs' then what type does it exist on?


Solution

  • $d is an implementation detail (what would be a private property in a more traditionally object-oriented language); there aren't type definitions for it because you aren't intended to use it directly. You can instead use the documented toDate method (e.g., selectedDate.toDate()).