Typescript conditional generic property inference

Viewed 42

I have a react component and want to make it bullet proof in terms of props.

My question is, can typescript actually infer this or did I do something wrong. Simplified version:

type DatePickerProps<Clearable extends boolean = false> = {
    clearable:Clearable
    value: DatePickerValue<Clearable>
    onChange: (value:DatePickerValue<Clearable>) => void
}

type DatePickerValue<Clearable extends boolean> = Clearable extends true ? Date | undefined : Date

function DatePicker<Clearable extends boolean = false>({clearable,value,onChange}:DatePickerProps<Clearable>){
    onChange(value)
    if(clearable === true)
        onChange(undefined)

}

Right now it's crying because of undefined and I'm aware that I can do something like this undefined as DatePickerValue<Clearable> to shut typescript up, but I don't want to shut up typescript.

As clearable is true in this case, it should be possible to set undefined.

To play around, here is the typescript playground

1 Answers

I will go with the answer from @jcalz

type DatePickerProps = {
    clearable?: false
    value: Date
    onChange: (value: Date) => void
} | {
    clearable: true
    value: Date | undefined
    onChange: (value: Date | undefined) => void
}

function DatePicker({ clearable, value, onChange }: DatePickerProps) {
    if (clearable) {
        onChange(value);
        onChange(undefined)
    } else {
        onChange(value);
    }
}

To be honest, please fix typescript. If you work with optionals and this kind of types, it's really fun to write multiple ifs in the code, to let typescript know whats going on.

Related