Closed
Description
Suggestion
Add generic types to window.fetch
π Search Terms
- window.fetch
- Response types
- json() fetch types
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
// declare function fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
declare function fetch<T = any>(input: RequestInfo, init?: RequestInit): Promise<Response<T>>;
// interface Response extends Body {
interface Response<T = any> extends Body<T> {
readonly headers: Headers;
readonly ok: boolean;
readonly redirected: boolean;
readonly status: number;
readonly statusText: string;
readonly trailer: Promise<Headers>;
readonly type: ResponseType;
readonly url: string;
clone(): Response;
}
interface Request extends Body { ... }
// interface Body {
interface Body<T = any> {
readonly body: ReadableStream<Uint8Array> | null;
readonly bodyUsed: boolean;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<Blob>;
formData(): Promise<FormData>;
json(): Promise<T>;
text(): Promise<string>;
}
π Motivating Example
type User = { user: string, password: string }
const response = await fetch<User>('https://...')
let user: User
if (response.ok) user = await response.json()
// Maybe better than ??
interface UserResponse extends Response {
json(): Promise<User>
}
const response: UserResponse = await fetch('https://...')