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

TypeScript中如何访问未导出的内部接口FileProps?

从导出的FileConfig中获取未导出的FileProps类型

问题场景

项目依赖的node_modules目录下的type.ts包含以下代码:

interface FileProps {
  type?: string;
  label?: string;
}

export interface FileConfig<
  Props = FileProps & {
    [additionalProperties: string]: any;
  }
> {
  name?: string;
  props?: Props;
}

需要编写foo函数,第一个参数要求匹配FileProps类型,第二个参数为FileConfig类型,但FileProps未导出无法直接导入,需通过FileConfig间接获取该类型。

实现方案

可以借助TypeScript的类型推断工具提取目标类型,代码如下:

import { FileConfig } from './type';

// 提取FileConfig默认泛型参数的类型
type FileConfigDefaultProps = FileConfig extends FileConfig<infer P> ? P : never;

// 移除交叉类型中的任意属性,得到原始FileProps类型
type ExtractedFileProps = Omit<FileConfigDefaultProps, string>;

function foo(props: ExtractedFileProps, config: FileConfig) {
  // 函数逻辑示例
  props.type; // 类型为string | undefined
  props.label; // 类型为string | undefined
  config.name; // 类型为string | undefined
}

原理说明

  1. 推断默认泛型参数:通过FileConfig extends FileConfig<infer P> ? P : never,TypeScript会自动推断出FileConfig的默认泛型参数类型,即FileProps & { [additionalProperties: string]: any }。
  2. 分离原始类型:使用Omit<..., string>移除交叉类型中所有字符串索引对应的任意属性,剩下的就是未导出的FileProps的所有成员。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:41:27