My goal is to set the return type of a function using TypeScript Generics. This way, the R
can be defined as anything I choose.
... Promise<R | string>
doesn't work for me.
Error
Error:(29, 9) TS2322: Type 'string' is not assignable to type 'R'. 'string' can be assigned to the constraint of type 'R', but 'R' might end up with a different subtype of constraint '{}'.
import { isString, } from '@redred/helpers';
interface P {
as?: 'json' | 'text';
body?: FormData | URLSearchParams | null | string;
headers?: Array<Array<string>> | Headers | { [name: string]: string };
method?: string;
queries?: { [name: string]: string };
}
async function createRequest<R> (url: URL | string, { as, queries, ...parameters }: P): Promise<R> {
if (isString(url)) {
url = new URL(url);
}
if (queries) {
for (const name in queries) {
url.searchParams.set(name, queries[name]);
}
}
const response = await fetch(url.toString(), parameters);
if (response.ok) {
switch (as) {
case 'json':
return response.json();
case 'text':
return response.text(); // <- Error
default:
return response.json();
}
}
throw new Error('!');
}
export default createRequest;