javascript - Flow can't assign property: assignment of computed property/element

I'm trying to add property in the object like this:

request(options:HttpRequestData): Promise<any> {
    options.headers = options.headers || {};

    options.headers['Accept'] = 'application/json';
    options.headers['Content-Type'] = 'application/json';  // Error

    return this._request(options);
}

But it has error:

options.headers['Content-Type'] = 'application/json';
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
assignment of computed property/element. Computed property/element cannot be assigned on possibly undefined value

HttpRequestData is a object type:

type HttpRequestData = {
    url:string,
    method:string,
    headers?:Object,
    body?:string,
};

Assiging just one value into options.header(in this case, 'Accept') works but it fails when I try two or more.

What the difference between single assigning and multiple assigning in Flow, and how to assign those properties into options.headers object?

Any advice will very appreciate it.

1 Answer

  1. Lori- Reply

    2019-11-15

    I solved this problem like this:

    request(options:HttpRequestData): Promise<any> {
        options.headers = options.headers || {};
    
        const modifiedHeaders = options.headers;
        modifiedHeaders['Accept'] = 'application/json';
        modifiedHeaders['Content-Type'] = 'application/json';
    
        options.headers = modifiedHeaders;
    
        return this._request(options);
    }
    

    Now no more error message.

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>