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

TypeScript如何推断外部接口中数组项的类型

获取TypeScript接口数组属性的元素类型

你可以通过两种方式轻松获取数组项的类型:

方法一:直接索引访问

利用TypeScript的索引访问特性,数组类型的[number]会直接返回它的元素类型,结合接口的属性索引就能拿到目标类型:

// file2
import { TestInterface } from './file1';

// 直接提取数组项的类型
type ItemType = TestInterface['items'][number];

function operateOnArrayItem(item: ItemType) {
  // 此时item会被正确推断为 { p1: string, p2: number }
  console.log(item.p1.toUpperCase());
  console.log(item.p2 + 1);
}

方法二:自定义工具类型(适合复用)

如果需要在多个地方提取数组元素类型,建议定义一个通用的工具类型,代码更易读且复用性强:

// file2
import { TestInterface } from './file1';

// 通用工具类型:提取任意数组/只读数组的元素类型
type ArrayElement<T> = T extends ReadonlyArray<infer U> ? U : never;

// 复用工具类型获取目标类型
type ItemType = ArrayElement<TestInterface['items']>;

function operateOnArrayItem(item: ItemType) {
  // 类型提示和检查完全正常
}

这两种方法都不需要修改外部文件,完全在当前文件中完成类型推导,完美适配你无法控制外部文件的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:37:02