I have a component which accepts onChange function (property).
Its definition is following:
onChange: (str: string | string[]) => void;
So, it means: str is either a string OR an array of string. When I use my component, I have a function which will be accepting only single string (setNoOfCols is a function from useState hook -> ):
const [noOfCols, setNoOfCols] = useState<string>('basic');
...
onChange: (value: string): void => setNoOfCols(value)
Unfortunately, I receive an error from Typescript saying that
TS2322: Type '(value: string) => void' is not assignable to type '(str: string | string[]) => void'.
Types of parameters 'value' and 'str' are incompatible.
Type 'string | string[]' is not assignable to type 'string'.
Type 'string[]' is not assignable to type 'string'.
How can I define a function for my component which will use only single string?
onChange: (value: any) => setNoOfCols(value as string). But you should deal with the issue, you should check if the value is a string or an array of strings.