TypeScript中如何在数组中使用不同对象类型并解决属性访问错误?
解决联合类型数组的属性访问问题
你的问题出在TypeScript对联合类型的类型检查机制上:当数组元素是OrType这种联合类型时,TypeScript无法确定每个元素具体是哪一种子类型,所以直接访问a或b会触发类型错误。下面是几种可行的解决方式:
1. 使用in操作符做类型守卫
通过检查属性是否存在来缩小类型范围,让TypeScript明确当前元素的具体类型:
type OrType = { a: string } | { b: number }; const testObj1: OrType = { a: 'string' }; const testObj2: OrType = { b: 12 }; const testArr1: OrType[] = [testObj1, testObj2]; // 处理数组元素 const result = testArr1.map((item) => { if ('a' in item) { return item.a; // 此时TypeScript知道item是{a: string}类型 } else { return item.b.toString(); // 统一返回string,或根据需求处理number类型 } });
2. 自定义类型守卫函数
如果类型判断逻辑更复杂,可以封装成类型守卫函数,提高代码复用性:
type OrType = { a: string } | { b: number }; // 自定义类型守卫,判断是否为{a: string}类型 function isTypeWithA(item: OrType): item is { a: string } { return 'a' in item; } const testArr1: OrType[] = [{ a: 'string' }, { b: 12 }]; const result = testArr1.map((item) => { if (isTypeWithA(item)) { return item.a; } else { return item.b; } });
3. 使用可辨识联合(推荐)
给联合类型的每个子类型添加一个唯一的区分字段(比如type),让TypeScript能通过这个字段快速确定元素类型,这是最规范的写法:
// 定义带区分字段的子类型 type TypeWithA = { type: 'a'; content: string }; type TypeWithB = { type: 'b'; content: number }; // 组合成联合类型 type OrType = TypeWithA | TypeWithB; const testArr1: OrType[] = [ { type: 'a', content: 'string' }, { type: 'b', content: 12 } ]; // 通过type字段直接区分类型 const result = testArr1.map((item) => { switch (item.type) { case 'a': return item.content; // string类型 case 'b': return item.content; // number类型 } });
内容的提问来源于stack exchange,提问作者enoveh
相关产品推荐
相关产品推荐

