PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How to typify axios request headers

 October 14, 2022     axios, javascript, typescript     No comments   

Issue

I'm trying to send request via Axios and I want to typify request headers. But I get an error.

I've created an interface Headers and used it to declare variable this._apiHeaders.

Error text:

The "Headers" type cannot be assigned to the "AxiosRequestHeaders" type.
There is no index signature for the "string" type in the "Headers" type (ts2322)
interface Headers {
    'X-Parse-Application-Id': string,
    'X-Parse-REST-API-Key': string
}
const response: ITest = await axios.get(
  this.formCorrectApiUrl(Endpoints.classes, DBObjectName),
  {
    headers: this._apiHeaders    // Here I get error
  }
);

Can someone please tell me how to fix the error and why it occures.


Solution

This can be implemented through "extends"

interface Headers extends AxiosRequestHeaders {
  'X-Parse-Application-Id': string
  'X-Parse-REST-API-Key': string
}

But I recommend making additionally the ability to create fields optional.

export type NonUndefined<T, E = undefined> = Pick<
  T,
  {
    [Prop in keyof T]: T[Prop] extends E ? never : Prop
  }[keyof T]
>

interface Headers extends AxiosRequestHeaders {
  'X-Parse-Application-Id': string
  'X-Parse-REST-API-Key': string
}

type AxiosHeaders = NonUndefined<Headers>

const headers: AxiosHeaders = {
  'X-Parse-Application-Id': 'test',
}


Answered By - Dmitriybo
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing