我正在尝试使用对象的选项属性动态更新对象。在代码中,我收到一个错误,其中显示 axiosOptions.headers[key]
(我在下面的代码示例中留下了评论)。
typescript 错误
Type 'string | undefined' is not assignable to type '"true" | "false"'.
Type 'undefined' is not assignable to type '"true" | "false"'.
我的代码
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);
我愿意接受有关如何解决此问题的建议。
最佳答案
TypeScript 不知道它不知道什么。它不知道在任何给定的 updateAxiosOptionsHeaders
运行中,key
是什么,因此它选择最严格的可能解释。当然,有很多不同的方法来解决这个问题,但是如果你想保持类型不变,你可以在函数中解决它:
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) {
if (key === 'IsRequireAdmin') {
// Note the default value if one isn't provided in newApiHeaders for some reason
axiosOptions.headers.IsRequireAdmin = newApiHeaders.IsRequireAdmin ?? 'false';
} else {
// ditto here
axiosOptions.headers[key] = newApiHeaders[key] ?? '';
}
}
};
const token: string = 'my_token';
const barCode: string = 'my_bar_code';
const domainName: string = 'www.mydomain.com';
const newApiHeaders: Partial<ApiHeaders> = {
'IsRequireAdmin': 'true',
'Authorization': `Bearer ${token}`,
'BarCode': barCode,
'DomainName': `DATA\\${domainName}`
};
updateAxiosOptionsHeaders(newApiHeaders);
修改部分见评论;您需要决定合理的默认值。
关于typescript - 使用 TypeScript 更新对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77567481/