Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material DateTimePicker onChange Typescript mismatch error

I have a following React + Material DatePicker code, reproduced literally from the respective documentation.

let App: React.FC = () => {

const [dateStart, handleDateStart] = useState(new Date());
const [dateEnd, handleDateEnd] = useState(new Date());

return (
    // Pickers from Material https://material-ui-pickers.dev/getting-started/usage
    <MuiPickersUtilsProvider utils={DateFnsUtils}>
        <DateTimePicker value={dateStart} onChange={handleDateStart}/>
        <DateTimePicker value={dateEnd} onChange={handleDateEnd}/>)
    </MuiPickersUtilsProvider>);

};

However, I write in TypeScript and it complains on the onChange bits:

Error:(28, 47) TS2322: Type 'Dispatch<SetStateAction<Date>>' is not assignable to type '(date: MaterialUiPickersDate) => void'.
Types of parameters 'value' and 'date' are incompatible.
 Type 'MaterialUiPickersDate' is not assignable to type 'SetStateAction<Date>'.
 Type 'null' is not assignable to type 'SetStateAction<Date>'.

TsConfig:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

I am new to React and Material, how can I avoid this error?

like image 779
onkami Avatar asked Jun 18 '20 14:06

onkami


1 Answers

The problem is that datepicker can return null as well (in case value is empty)

Working example:

const [date, setDate] = React.useState<Date | null>(new Date());

return (
  <DatePicker
    value={date} 
    onChange={newDate => setDate(newDate)} 
  />
)

like image 162
Dmitriy Kovalenko Avatar answered Oct 30 '22 00:10

Dmitriy Kovalenko