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
相关产品推荐
相关产品推荐

