Reputation: 26518
depending on the type of a parameter I'd like to type the return. Similar to function overload, but using mapped types.
const requestX = async(
id?: string | undefined,
): Promise<(typeof id) extends string ? X: X[]> =>
fetch(......)
However, the return is always typed as X[]
. What is the proper way to do it?
Upvotes: 0
Views: 204
Reputation: 184376
Unless you use overloads as suggested by Aleksey L., you need a generic type argument, otherwise typeof id
is resolved statically to string | undefined
which does not help in the mapping.
Generics example:
const requestX = async <ID extends string | undefined = undefined>(id?: ID)
: Promise<ID extends string ? X : X[]> =>
fetch(...);
const x = requestX() // Promise<X[]>
const y = requestX('123'); // Promise<X>
Upvotes: 1