我试图动态更新一个对象的选项属性从一个对象.在代码中,我得到一个错误,它说axiosOptions.headers[key]
(我在下面的代码示例中留下了注释).
TypeScript Error
Type 'string | undefined' is not assignable to type '"true" | "false"'.
Type 'undefined' is not assignable to type '"true" | "false"'.
My Code
type ApiHeaders = {
Accept: string;
'Content-Type': string;
IsRequireAdmin: 'true' | 'false';
Authorization?: string;
BarCode?: string;
DomainName?: string;
};
interface AxiosOptions {
params?: any;
data?: any;
headers: ApiHeaders;
}
const axiosOptions: AxiosOptions = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
IsRequireAdmin: 'false'
}
};
const updateAxiosOptionsHeaders = (newApiHeaders: Partial<ApiHeaders>): void => {
let key: keyof Partial<ApiHeaders>;
for (key in newApiHeaders) axiosOptions.headers[key] = newApiHeaders[key]; // <----------- typescript error
};
const token: string = 'my_token';
const barCode: string = 'my_bar_code';
const domainName: string = 'www.mydomain.com';
const newApiHeaders: Omit<ApiHeaders, 'Content-Type' | 'Accept'> = {
'IsRequireAdmin': 'true',
'Authorization': `Bearer ${token}`,
'BarCode': barCode,
'DomainName': `DATA\\${domainName}`
};
updateAxiosOptionsHeaders(newApiHeaders);
我对如何解决这个问题的建议持开放态度.