cferdinandi / atomic

A tiny, Promise-based vanilla JS Ajax/HTTP plugin with great browser support.
MIT License
540 stars 78 forks source link

Provide TypeScript type definition file #93

Closed The-MAZZTer closed 3 years ago

The-MAZZTer commented 3 years ago

Currently the package provides no TypeScript type definitions which can make it not possible to use from TypeScript if you have strict mode on.

I created some type definitions below, they seem to work fine with one exception: atomicjs exports a function instead of an object with functions in it; the former is not allowed by ES6 so TypeScript is not happy and requires you to enable some compatibility switches to import it. Atomic exporting an object with a function in it would bring it in line with ES6 standards as I understand. But the following type definition matches the current stable package:

declare module "atomicjs" {
    type ResponseTypeStrings = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
    type ResponseTypes<T> = 
        T extends "" ? string :
        T extends "arraybuffer" ? ArrayBuffer :
        T extends "blob" ? Blob :
        T extends "document" ? Document :
        T extends "json" ? any :
        T extends "text" ? string :
        never;

    type AtomicOptions = {
        method?: string,
        username?: string,
        password?: string,
        data?: object,
        headers?: Record<string, string>,
        timeout?: number,
        withCredentials?: boolean
    };

    type AtomicOptionsWithResponseType<T extends ResponseTypeStrings> = AtomicOptions & {
        responseType: T
    };

    type AtomicPromise<T> = Promise<T> & {
        cancel: () => void
    };

    function atomic(url: string, options: AtomicOptions | undefined): AtomicPromise<{data: string, xhr: XMLHttpRequest}>;
    function atomic<T extends ResponseTypeStrings>(url: string, options: AtomicOptionsWithResponseType<T>): AtomicPromise<{data: ResponseTypes<T>, xhr: XMLHttpRequest}>
    export = atomic;
}

Other possible areas for improvement include generic (eg <>) support for mapping JSON return values to a specific type.

I created this for use in a Chrome extension project, where I was compiling TypeScript down with webpack for the background service worker. My intention was to use a Promise-type model (using atomic) instead of XMLHttpRequest. But service workers don't support XML:HttpRequest so I couldn't use atomic anyway. But I don't want these definitions I wrote to go to waste.

cferdinandi commented 3 years ago

Hard pass. Typescript sucks.

cferdinandi commented 3 years ago

Sorry, that came across is a lot more rude than I intended.

what I meant to say was that I have no interest in adding support for a tool I don’t use and strongly dislike.