Importing RangeValue type from Ant Design

Viewed 1607

Working on an update to Replace Moment.js with date-fns for Ant Design's DatePicker based on the documentation which seems to be working fine.

Mainly it's suggesting to create the following:

import dateFnsGenerateConfig from 'rc-picker/lib/generate/dateFns'
import generatePicker from 'antd/es/date-picker/generatePicker'

const DatePicker = generatePicker<Date>(dateFnsGenerateConfig)

Then use the component as below:

<DatePicker.RangePicker
          placeholder={['From', 'To']}
          onChange={range => setRange(range)}
          value={range}
/>

For the above the following state has been created with the type RangeValue:

const [range, setRange] = useState<RangeValue<Date>>(
   [from, to]
)

The RangeValue type has been imported as the following:

import { RangeValue } from 'rc-picker/lib/interface'

// technically:
// import { RangeValue } from '../../../../node_modules/rc-picker/lib/interface'

Question:

I found only this comment in one of the questions here where we have similar conversation.

Is there any way to import the RangeValue type, maybe from Ant Design? Thank you!

1 Answers

I was having a hard time typing antd values. Seems like they don't provide any easy option. Eventually ended up on using this:

type RangeValue = Parameters<NonNullable<React.ComponentProps<typeof DatePicker.RangePicker>['onChange']>>[0]

That will pull out the type of the first argument that is sent into the onChange function. It will also work with other events (onClick, onBlur etc). You can also pull out the types of other arguments simply by increasing the number in the square brackets. Now you can assign this type to your onChange handler:

const handleOnChange = (dates: RangeValue, formattedDates: string[]) => {
//do something
return dates 
}
Related