In React, I'm trying to set a conditional type in a function parameter based on whether a prop is passed in the component.
Here is an example, I have this component:
const DatePicker = ({ handleDateChange, value, objectKey, }: { handleDateChange: (value: Dayjs | { [x: string]: Dayjs }) => void; value: Dayjs; objectKey?: string; }) => JSX
What I want to do is, if "objectKey" is passed as props, then the type of "value" parameter in handleDateChange function will be { [x: string]: Dayjs }, otherwise it will be value: Dayjs.
Does anyone know how to implement this?
You can achieve similar effects through function overloading.
Using this method, DatePicker can only be called according to your definition, but the implementation part does not know the association between handleDateChange and objectKey, so it still needs to be handled explicitly.
Without knowing any details about DatePicker, I think it's better to just use a signature and let the parent component make adjustments to the DatePicker, rather than having the DatePicker handle special cases from the parent component.