11ty/eleventy-fetch

Types?

gBasil opened this issue · 5 comments

Would it be feasible to have TypeScript types (.d.ts) available for this package? There doesn't seem to be anything on DefinitelyTyped.

Happy to merge a PR!

I tried to write some types, but I was defeated by TypeScript features I don't fully grasp (namely overloading the method in a way that would set the right output type depending on type option).

This is what I've been using:

declare module "@11ty/eleventy-fetch" {

    type FetchType =
        | "json"
        | "buffer"
        | "text";

    type EleventyFetchOptionsBase<TType extends FetchType> = {
        type: TType;
        directory?: string;
        concurrency?: number;
        fetchOptions?: RequestInit;
        dryRun?: boolean;
        removeUrlQueryParams?: boolean;
        verbose?: boolean;
        hashLength?: number;
        duration?: string;
        formatUrlForDisplay?: (url: string) => string;
    }

    type EleventyFetch = <TReturn, TType extends FetchType = "json">(url: string, options: EleventyFetchOptionsBase<TType>) =>
        Promise<
            TType extends "json" ? TReturn :
            TType extends "buffer" ? Buffer :
            TType extends "text" ? string :
            never
        >;

    const fetch: EleventyFetch;
    export default fetch;
}

I think it handles most scenarios. @gBasil do you want to see if that handles at least your use-case?

I ended up switching off of @11ty/eleventy-fetch and writing my own basic implementation, but I hope your types are useful for others who stumble upon this issue in the future :)

No worries @gBasil! I'll make a pr either way.