Reputation:
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
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"
Upvotes: 0