Ad

Interface For Http Headers In The Fetch Method

- 1 answer

I have a method that fires a fetch function. It also sets headers over which type I would like to have control.

    // Request headers
    let headers: HttpHeaders = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };

    // Checks if user have x-auth-token cookie
    const token = getCookie(AUTH.COOKIE_NAME);
    if (token !== null) {
        headers = {
            ...headers,
            [AUTH.API_TOKEN]: token
        };
    }

    // Request body
    const request = {
        method,
        headers,
        body: JSON.stringify(body)
    };

    if (body || method.toUpperCase() === HttpMethod.GET) {
        delete request.body;
    }

I have also enum, which holds all allowed headers:

export enum HttpHeader {
    ACCEPT = 'Accept',
    CONTENT_TYPE = 'Content-Type',
    X_AUTH_TOKEN = 'x-auth-token'
}

I already know that you can't specify enum as the expected index value in the ts interface. Can you give me another option to control http request headers? I saw the idea of using an array of objects, but I have the impression that it is a bit of a form over content.

Ad

Answer

You can use an enum to define a type that has all the enum values as keys using a mapped type (what you can't do is have an enum as an index parameter).

The predefined Record and Partial mapped types will do the job nicely:


type HttpHeaders = Partial<Record<HttpHeader, string>>

export enum HttpHeader {
    ACCEPT = 'Accept',
    CONTENT_TYPE = 'Content-Type',
    X_AUTH_TOKEN = 'x-auth-token'
}

// Request headers
let headers: HttpHeaders = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
};

headers = {
    ...headers,
    [HttpHeader.X_AUTH_TOKEN]: "token"
};


Play

Ad
source: stackoverflow.com
Ad