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

TypeScript泛型ComponentMap实现嵌套接口自动补全及Partial转Required

问题:为嵌套接口实现自动补全的ComponentMap类型

我正在尝试创建一个类型,将接口转换为特殊数组类型以获得更优的自动补全效果。目前已实现代码如下:

type UnStyleKey<K extends PropertyKey> = K extends `${infer P}Style` ? Uncapitalize<P> : K;

interface ComponentMap<T = unknown> {
  key: UnStyleKey<keyof T>;
  subKeys?: Array<ComponentMap<T>>;
  prefix?: string;
}

示例接口

interface TextInputStyle {
  mainContainerStyle: IOStyle<ContainerStyleProps, TextInputRestProps>;
  inputContainerStyle: IOStyle<ContainerStyleProps, TextInputRestProps>;
  iconStyle: IOStyle<IconStyleProps, TextInputRestProps>;
  clearIconStyle: Partial<IconButtonStyle>;
  inputStyle: IOStyle<InputStyleProps, TextInputRestProps>;
  fieldMessageStyle: FieldMessageStyle;
}

interface AutoCompleteStyle {
  mainContainerStyle: IOStyle<ContainerStyleProps, AutoCompleteRestProps>;
  textInputStyle: Partial<TextInputStyle>;
  autoCompleteItemsContainerStyle: IOStyle<ContainerStyleProps, AutoCompleteRestProps>;
  autoCompleteItemStyle: Partial<AutoCompleteItemStyle>;
  loadingTypographyStyle: IOStyle<TypographyStyleProps, AutoCompleteRestProps>;
  noOptionsTypographyStyle: IOStyle<TypographyStyleProps, AutoCompleteRestProps>;
}

当前仅能获得第一层属性的自动补全,无法为textInputStyle这类嵌套接口的key提供正确的自动补全。此外,希望将所有Partial类型转换为非Partial类型,请问如何修改ComponentMap让subKeys正确适配嵌套接口的类型?


解决方案

要实现嵌套自动补全并处理Partial转原始类型,需要调整ComponentMap的泛型逻辑,让subKeys的类型依赖当前key对应的属性类型:

步骤1:定义工具类型移除Partial包装

type UnPartial<T> = T extends Partial<infer U> ? U : T;

步骤2:重构ComponentMap类型

type UnStyleKey<K extends PropertyKey> = K extends `${infer P}Style` ? Uncapitalize<P> : K;

type ComponentMap<T = unknown> = {
  [K in keyof T]: {
    key: UnStyleKey<K>;
    subKeys?: ComponentMap<UnPartial<T[K]>>[];
    prefix?: string;
  }
}[keyof T];

关键说明

  • UnPartial:自动将Partial<X>转换为X,满足你将Partial类型转为非Partial的需求;
  • 映射类型遍历:通过[K in keyof T]为每个属性生成专属结构,subKeys的类型会根据当前属性的真实类型(去掉Partial后)动态推导对应的ComponentMap数组;
  • 联合类型提取:最后用[keyof T]提取所有可能的结构组成联合类型,这样自动补全时,选择不同的key会自动匹配对应的嵌套subKeys类型。

效果验证

当使用ComponentMap<AutoCompleteStyle>时:

  • 选择key: "textInput"(对应原textInputStyle),subKeys会自动补全TextInputStyle所有转换后的key(如mainContainer、inputContainer等);
  • 所有被Partial包裹的嵌套类型都会被自动转为原始类型,确保嵌套层级的自动补全准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:41:03