TypeScript混合类型数组访问对象属性报错的原因及解决
TypeScript混合类型数组访问属性报错的原因与解决方法
报错原因
TypeScript 会自动推断 testData 的类型为 (string[] | { properties: { number: number; name: string; }; second: string; })[],即数组元素是对象类型和字符串数组类型的联合类型。
虽然你明确 testData[0] 是对象,但 TypeScript 是静态类型检查机制,它仅基于代码定义推断类型,不会执行代码确认元素实际类型。因此它判定 testData[0] 有可能是字符串数组(而数组不存在 second 属性),从而抛出类型错误。
正确获取属性的方法
1. 用元组类型明确数组结构
由于你的数组每个位置的元素类型是固定的(第一个为对象,第二个为字符串数组),可以直接通过元组类型定义 testData,让 TypeScript 明确每个索引对应的元素类型:
const testData: [ { properties: { number: number; name: string; }; second: string; }, string[] ] = [ { properties: { number: 1, name: 'haha' } , second: 'this type'}, ['one', 'two', 'three'], ]; // 此时 testData[0] 类型确定,直接访问 second 无报错 const wantToGet = testData[0].second;
2. 使用类型断言指定类型
如果不想修改数组定义,可通过类型断言直接告知 TypeScript 当前元素的具体类型:
const testData = [ { properties: { number: 1, name: 'haha' } , second: 'this type'}, ['one', 'two', 'three'], ]; // 断言 testData[0] 为目标对象类型 const wantToGet = (testData[0] as { properties: { number: number; name: string; }; second: string; }).second;
若该类型会重复使用,建议先定义类型别名简化代码:
type DataObject = { properties: { number: number; name: string; }; second: string; }; const testData = [ { properties: { number: 1, name: 'haha' } , second: 'this type'}, ['one', 'two', 'three'], ]; const wantToGet = (testData[0] as DataObject).second;
3. 通过类型守卫做运行时检查
使用类型守卫在代码分支中让 TypeScript 自动推断类型,这种方式兼顾类型安全与运行时校验:
const testData = [ { properties: { number: 1, name: 'haha' } , second: 'this type'}, ['one', 'two', 'three'], ]; if ('second' in testData[0]) { // 此分支内 TypeScript 会自动识别 testData[0] 为包含 second 属性的对象 const wantToGet = testData[0].second; }
内容的提问来源于stack exchange,提问作者lemonshampoo
相关产品推荐
相关产品推荐

