How do I make this compile.
type Matchmaker = (data: MatcherData, name: string) => string
type MatcherData = RegExp | Array<string>
function makeDataUser(fU: (data: MatcherData) => string): Matchmaker {
return function (data: MatcherData, name: string): string {
return fU(data) + name;
}
}
const user1 = makeDataUser((data: MatcherData): string => {
if (typeof data === 'regexp') {
if ("lkajdsf".match(data)) {
return "yes";
}
return "no";
} else {
return data.join('');
}
});
const user2 = makeDataUser((data: MatcherData): string => {
if (typeof data !== 'regexp') {
return "yes";
} else {
return "no";
}
}
const mRegexUser = user1(/regex/, 'name');
const mArrayUser = user2(['lkajf'], 'name2');
I want a function parameter to be either of two types and use it in either case.
The trick is I know user1
always expects RegExp
, and user2
always expects Array<string>
. But I want to provide them with a generic function above.