如何从TypeScript接口的嵌套对象数组中提取对象类型?
获取TypeScript嵌套数组内的对象类型
给定自动生成的TypeScript接口:
export interface StaticPageLeftMenuV1 { id: string status: 'draft' | 'published' environments: ('dev' | 'staging' | 'production')[] created_by?: string | User last_modified_by?: string | User list?: { header?: string items?: { relation?: { value: string | StaticPageV1 relationTo: 'static-page-v1' } custom_link_text?: string custom_link_url?: string custom_link_color?: string id?: string }[] id?: string }[] }
需要声明obj.list[0].items[0]对应的对象类型。虽然可以通过StaticPageLeftMenuV1['list']获取list的类型,但得到的是包含undefined的数组类型,直接用StaticPageLeftMenuV1['list'][0]['items'][0]的写法会报错——因为list和items都是可选属性(可能为undefined),且数组索引[0]在数组为空的场景下也不符合类型规范。
解决方案
可以通过NonNullable排除可选属性的undefined可能性,再用[number]获取数组的元素类型:
- 分步获取类型:
// 先获取list数组的元素类型(排除undefined) type ListItem = NonNullable<StaticPageLeftMenuV1['list']>[number]; // 再获取items数组的元素类型(排除undefined) type Item = NonNullable<ListItem['items']>[number];
- 合并为一行写法:
type Item = NonNullable<NonNullable<StaticPageLeftMenuV1['list']>[number]['items']>[number];
说明
NonNullable<T>用于移除类型T中的undefined和null,确保我们处理的是有效的数组类型。- 用
[number]获取数组的元素类型,比[0]更通用可靠,因为它直接指向数组的元素类型定义,不受数组长度影响。
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

