I have the following code: a function which returns an option from an array. The options could be strings or regexes, and the return value will follow suit.
const pick = (options: Array<string | RegExp>): string | RegExp =>
options[Math.floor(Math.random() * options.length)];
const myOptions = ['hello', 'goodbye']
const randomId: string = pick(myOptions);
This raises this error:
Cannot assign
pick(...)
torandomId
becauseRegExp
[1] is incompatible with string [2].Flow(incompatible-type)
Why is this?
Ok, building from the comments, there are several issues here:
Using a generic, we can redefine the function like this:
const pick = <T>(options: Array<T>): T =>
options[Math.floor(Math.random() * options.length)];
This works fine.