In the code below, I get an error on the line props.onChange(e.target.value as typeof props.value): "Argument of type 'string | string[]' is not assignable to parameter of type 'string & string[]'."
e.target.value is of type unknown. If onChange was only of type (value: string) => void, then I would just cast like so: props.onChange(e.target.value as string) and that would work. Likewise for string[].
There's probably a way to make this work with generics, right? I have not figured out how.
(I include the type of e for clarity; it is not necessary to make that explicit).
import { MenuItem, Select } from '@material-ui/core';
import React, { ChangeEvent, FC } from 'react';
interface SingleProps {
value: string;
onChange: (value: string) => void;
multiple: false;
}
interface MultiProps {
value: string[];
onChange: (value: string[]) => void;
multiple: true;
}
const ReportDateSelect: FC<SingleProps | MultiProps> = props => (
<Select
value={props.value}
onChange={(e: ChangeEvent<{ name?: string; value: unknown }>) =>
props.onChange(e.target.value as typeof props.value)
}
multiple={props.multiple}
>
{[1, 2, 3].map((c, i) => (
<MenuItem key={i} value={c}>
{c}
</MenuItem>
))}
</Select>
);
export default ReportDateSelect;