英文:
Pick error "Type 'Pick<TypeObject, "...">' cannot be used as an index type."
问题
尝试修改我的 axios 封装器,但无法弄清楚为什么会出现这个 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;
}
英文:
Trying to modify my axios wrapper and can't figure out why I'm getting this typescript error...
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;
}
答案1
得分: 1
这不真正符合 Pick
的用法模式。对于你的情况,你只需要使用 Headers
的 keyof
:
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;
}
如果你的对象中还有不同的值类型(这在头部对象中似乎不太可能),你可以使用泛型约束:
export const updateAxiosOptionsHeaders = <K extends keyof Headers>(
key: K,
value: Headers[K]
): void => {
axiosOptions.headers[key] = value;
}
英文:
This doesn't really meet the usage pattern of Pick
. You just need keyof Headers
for your case:
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;
}
Should you also have different value types in your object (which seems unlikely for a headers object), you can use a generic constraint:
export const updateAxiosOptionsHeaders = <K extends keyof Headers>(
key: K,
value: Headers[K]
): void => {
axiosOptions.headers[key] = value;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论