0

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?

1
  • You can just cast it to 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. Commented Jul 24, 2020 at 11:44

1 Answer 1

1

You can avoid this error by using the correct signature while using useState like below

const [noOfCols, setNoOfCols] = useState<string|string[]>('basic');

Or you can update your onChange type definition like this :

type onChange = ((str: string|string[]) => void) | ((str: string[]) => void);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.