user145072
user145072

Reputation:

TypeScript: return a union of the input string array's literal values?

Can I type a function such that it takes a string[] and the output is a string union?

For example, given this function:

function myfn(strs: string[]) {
  return strs[0];
}

If I call it like:

myfn(['a', 'b', 'c']) // => return type is: 'a' | 'b' | 'c'

Is this possible in TypeScript?

Upvotes: 0

Views: 132

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37938

You can add generic parameter to describe the array item, typescript will be able to infer it from provided value:

function myfn<T extends string>(strs: T[]) {
  return strs[0];
}

const result = myfn(['a', 'b', 'c']) // "a" | "b" | "c"

Playground

Upvotes: 0

Related Questions