Skip to content

Generic types on lib.dom window fetchΒ #44000

Closed
@caenguidanos

Description

@caenguidanos

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://...')

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions