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

如何结合TypeScript使用Material UI日期选择器?Dayjs类型报错问题

解决Dayjs访问$d的TypeScript类型问题

Dayjs的$d是框架内部的私有属性,官方提供的TypeScript类型定义并没有对外暴露这个属性,所以直接访问会触发类型错误。不建议直接依赖私有属性,因为这类属性可能随版本更新发生变化,导致代码不稳定。

正确的做法是使用Dayjs官方提供的公开API来获取原生日期对象:

  • 调用Dayjs实例的toDate()方法,它会返回标准的Date类型,完全符合TypeScript的类型规范。

修改你的代码示例如下:

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={() => {
                if (selectedDate) {
                    // 使用toDate()获取原生Date对象
                    const nativeDate = selectedDate.toDate();
                    console.log(nativeDate);
                }
            }}>click</button>
            </Stack>
        </div>
    )
}

export default BookingComponent

如果出于特殊需求必须访问$d(强烈不推荐),可以通过类型断言临时绕过类型检查,但要自行承担版本变更的风险:

if (selectedDate) {
    const internalDate = (selectedDate as unknown as { $d: Date }).$d;
    console.log(internalDate);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:42:12