0

I started working with angular HttpHeaders but could not understand one of the parameters of its constructor which is [name: string]: string , here is the constructor from the docs :

constructor(headers?: string | { **[name: string]: string** | string[]; })

could anyone explain the type of that object or what it does refer to?

Ameerudheen.K
  • 657
  • 1
  • 11
  • 31
redd77
  • 307
  • 5
  • 11

3 Answers3

5

This is called an index signature.

So the full type declaration you shared headers?: string | { [name: string]: string | string[]; } is saying that headers can be 1 of 2 types: a string, or an object with a specific shape.

For example:

  • string: "some value"
  • object (with a string value): { some: "value" }
  • object (with a string[] value): { some: ["value", "foo"] }

The index signature { [name: string]: string | string[]; } is specifically saying that any key name that is a string can be used and it's value can be either a string or an array of strings (string[]). The name in [name: string] actually has no significance.

skovy
  • 5,430
  • 2
  • 20
  • 34
2

This is a way of declaring an Object, or you could say a dictionary, a key/value pair. Where you do not need to define the properties (different from an interface), you just say that the key will be of type string and the value of type (in this case) string | string[].

So, when you set your headers as {'Accept': 'application/json'}, for example, you are creating a pair where key is 'Accept', of type string, and this key's value is 'application/json', also of type string.

That way of declaring a type let's you have, of course, multiple dynamic properties, so you could end up with:

const headers = {
  'Accept': 'application/json',
  'Authorization': `Bearer ${jwt}`,
};
João Ghignatti
  • 2,281
  • 1
  • 13
  • 25
1

It means you can just pass in headers as one string, or object list of string header definitions. If you're looking on the best way to set your headers check this:

 let headers: HttpHeaders = new HttpHeaders();
    headers = headers.append(
    'Accept',
     'text/html,application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0. 8'  
    );

or this answer here:

How to correctly set Http Request Header in Angular 2

Nadhir Falta
  • 5,047
  • 2
  • 21
  • 43