Reputation: 11
I would like to have a function that accepts either a string or an array of strings. Then it would return the same data type entered in. Here is an example of the code that is currently not working.
export default <T extends string | string[]>(s: T): T =>
Array.isArray(s)
? s.map(handleString)
: handleString(s)
Upvotes: 0
Views: 23
Reputation: 85012
I would do this with function overloading:
const handleString = (val: string) => val;
function example(s: string): string;
function example(s: string[]): string[];
function example(s: string | string[]): string | string[] {
return Array.isArray(s)
? s.map(handleString)
: handleString(s)
}
const a = example('a'); // a's type is string
const b = example(['b']); // b's type is string[]
Upvotes: 2