axios Pick错误“类型'Pick< TypeObject,“...">'不能用作索引类型,”

nhhxz33t  于 2023-06-05  发布在  iOS
关注(0)|答案(1)|浏览(226)

试图修改我的axios Package 器,无法弄清楚为什么我得到这个 typescript 错误...

type Headers = {
  Accept: string;
  'Content-Type': string;
  Authorization?: string;
}

export interface AxiosOptions {
  params?: any;
  data?: any;
  headers: Headers;
}

const axiosOptions: AxiosOptions = {
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
};

export const updateAxiosOptionsHeaders = (
    key: Pick<Headers, "Accept" | "Content-Type" | "Authorization">,
    value: string
  ): void => {
  axiosOptions.headers[key] = value;
}

cqoc49vn

cqoc49vn1#

这并不真正符合Pick的使用模式。你只需要keyof Headers就可以了:

type Headers = {
  Accept: string;
  'Content-Type': string;
  Authorization?: string;
}

export interface AxiosOptions {
  params?: any;
  data?: any;
  headers: Headers;
}

const axiosOptions: AxiosOptions = {
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
};

export const updateAxiosOptionsHeaders = (
    key: keyof Headers,
    value: string
  ): void => {
  axiosOptions.headers[key] = value;
}

Playground链接
如果你的对象中也有不同的值类型(对于headers对象来说似乎不太可能),你可以使用一个通用约束:

export const updateAxiosOptionsHeaders = <K extends keyof Headers>(
    key: K,
    value: Headers[K]
  ): void => {
  axiosOptions.headers[key] = value;
}

相关问题