I want to define the function return type via TypeScript Generics. So the R
can be anything what I will define.
... Promise<R | string>
is not solution for me
Error
Error:(29, 9) TS2322: Type 'string' is not assignable to type 'R'. 'string' is assignable to the constraint of type 'R', but 'R' could be instantiated 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;
createRequest<number>(/*some arguments*/)
and have your function return a promise that resolves to a number? – Nicholas Tower