You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript接口中引用数组内对象的类型?

提取数组元素类型的几种方法

针对你定义的这个接口:

interface MyInterface {
  prop1: {
    nestedProp1: number;
    nestedProp2: string;
  }[];
};

要获取prop1数组里的对象类型,有几种简单实用的方式:

  • 索引访问语法(最直接)
    直接在数组类型后面追加[number],TypeScript会自动解析出数组的元素类型:
type NestedType = MyInterface['prop1'][number];
// 此时 NestedType 等价于 { nestedProp1: number; nestedProp2: string; }
  • 复用泛型工具(适合复杂场景)
    如果需要处理更复杂的数组类型(比如包含数组的联合类型),可以先定义一个通用的工具类型,再复用它提取元素类型:
type ArrayElement<T> = T extends Array<infer U> ? U : never;
type NestedType = ArrayElement<MyInterface['prop1']>;

这种方式的优势在于ArrayElement可以重复用于其他数组类型的元素提取,不用每次都写重复的逻辑。

内容的提问来源于stack exchange,提问作者Connor Mooneyhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:27:39