使用TypeScript更新对象属性时遇类型错误,求解决方案
动态更新对象属性时的TypeScript错误修复方案
问题描述
尝试通过一个对象的可选属性动态更新另一个对象,代码中axiosOptions.headers[key]处触发TypeScript错误。
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);
修复方案
错误原因
Partial<ApiHeaders>会将原类型的所有属性转为可选,导致newApiHeaders[key]的类型为string | 'true' | 'false' | undefined。但axiosOptions.headers中的IsRequireAdmin等属性是必填的'true' | 'false',TypeScript无法保证newApiHeaders[key]不会是undefined,因此抛出类型不兼容错误。
具体修复方法
方法1:非空断言(简单直接)
用!断言newApiHeaders[key]不为undefined,同时将循环的key类型改为keyof ApiHeaders(和原类型一致更准确):const updateAxiosOptionsHeaders = (newApiHeaders: Partial<ApiHeaders>): void => { let key: keyof ApiHeaders; for (key in newApiHeaders) { axiosOptions.headers[key] = newApiHeaders[key]!; } };方法2:类型守卫过滤undefined(更严谨)
先判断属性值是否存在,再执行赋值操作:const updateAxiosOptionsHeaders = (newApiHeaders: Partial<ApiHeaders>): void => { let key: keyof ApiHeaders; for (key in newApiHeaders) { const value = newApiHeaders[key]; if (value !== undefined) { axiosOptions.headers[key] = value; } } };方法3:使用Object.assign简化逻辑
直接用Object.assign合并对象,TypeScript能自动处理类型推导,避免循环中的类型问题:const updateAxiosOptionsHeaders = (newApiHeaders: Partial<ApiHeaders>): void => { Object.assign(axiosOptions.headers, newApiHeaders); };
内容的提问来源于stack exchange,提问作者Fiddle Freak
相关产品推荐
相关产品推荐

