TypeScript中如何将HTTP响应的0/1映射为布尔类型适配接口?
解决TypeScript接口与HTTP响应类型不匹配问题
问题场景
现有用于映射HTTP响应的TypeScript接口:
interface Person { firstName: string; lastName: string; active: boolean; }
后端返回的示例响应中,active字段是数字1或0,而非接口定义的布尔值:
{ firstName: 'John', lastName: 'Brown', active: 1 }
直接赋值或使用类型断言(const person = response as Person)后,person.active仍为数字类型,不符合接口预期。且无法修改后端,同时响应可能包含上百个对象的数组,需高效处理类型转换。
核心原因
TypeScript的类型注解/断言仅作用于编译时类型检查,不会在运行时自动转换数据类型。要让active变成布尔值,必须添加运行时转换逻辑。
解决方案
方案1:泛型批量转换函数(高效处理单对象/数组)
编写通用转换函数,自动处理单个对象或数组的类型转换,遍历几百个对象的性能开销可忽略:
interface Person { firstName: string; lastName: string; active: boolean; } function transformPersonResponse<T extends Person | Person[]>(response: T): T { const transformSingle = (item: any): Person => ({ ...item, active: Boolean(item.active) // 将1/0转为true/false }); return Array.isArray(response) ? response.map(transformSingle) as T : transformSingle(response) as T; } // 单个对象转换示例 const singleResponse = { firstName: 'John', lastName: 'Brown', active: 1 }; const person = transformPersonResponse(singleResponse); console.log(person.active); // 输出 true // 数组转换示例 const arrayResponse = [ { firstName: 'John', lastName: 'Brown', active: 1 }, { firstName: 'Jane', lastName: 'Doe', active: 0 } ]; const people = transformPersonResponse(arrayResponse); // 每个对象的active均为布尔值
方案2:Proxy延迟转换(适合大数据量场景)
使用Proxy拦截属性访问,仅在读取active字段时才做类型转换,无需提前遍历整个数组:
interface Person { firstName: string; lastName: string; active: boolean; } function createTypedProxy<T>(obj: any): T { return new Proxy(obj, { get(target, prop) { const value = target[prop]; // 针对active字段做数字转布尔的处理 if (prop === 'active' && typeof value === 'number') { return Boolean(value); } return value; } }) as T; } // 使用示例 const response = { firstName: 'John', lastName: 'Brown', active: 1 }; const person = createTypedProxy<Person>(response); console.log(person.active); // 输出 true
方案3:类替代接口(自带转换逻辑)
用类定义数据结构,在构造函数中自动完成类型转换:
class Person { firstName: string; lastName: string; active: boolean; constructor(data: { firstName: string; lastName: string; active: number }) { this.firstName = data.firstName; this.lastName = data.lastName; this.active = Boolean(data.active); } } // 单个对象转换 const singleResponse = { firstName: 'John', lastName: 'Brown', active: 1 }; const person = new Person(singleResponse); // 数组转换 const arrayResponse = [/* 响应数组 */]; const people = arrayResponse.map(item => new Person(item));
内容的提问来源于stack exchange,提问作者Darrell
相关产品推荐
相关产品推荐

