Camden Ko
Camden Ko

Reputation: 11

Typescript accept and return constrained generic

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

Answers (1)

Nicholas Tower
Nicholas Tower

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[]

Playground link

Documentation on overloading

Upvotes: 2

Related Questions