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

TypeScript映射类型+条件类型导致IDE自动补全失效求助

问题:TypeScript泛型下样式对象属性自动补全失效

需求

需要实现一个createStyles函数,接收的对象包含两种样式类型:

  • 基于预定义主题类型的Emotion CSS插值
  • 带有显式参数的Getter函数,返回上述CSS插值类型
    通过键名是否以get前缀区分这两种类型,示例代码如下:
const styles = createStyles({
  regular: (theme) => ({ color: theme.palette.red }),

  getFancy: (isDisabled: boolean) => (theme) => ({
    color: theme.palette[isDisabled ? 'gray' : 'red']
  }),
});

问题现象

IDE悬停时能正确推断类型,构建styles对象时类型检查也正常,但对象属性的自动补全功能失效。

尝试过的方案

方案一

type GetterKey = `get${Capitalize<string>}`;

const createStyles = <
  TStyles extends {
    [K in keyof TStyles]: K extends GetterKey
      ? (...args: any[]) => Interpolation<Theme>
      : Interpolation<Theme>;
  }
>(
  styles: TStyles
) => styles;

该方案能完美解析最终对象,类型检查正常,但所有CSS对象的属性自动补全失效。

方案二

const createStyles = <
  TStyles extends {
    [K in keyof TStyles extends GetterKey
      ? GetterKey
      : Exclude<keyof TStyles, GetterKey>]: K extends GetterKey
      ? (...args: any[]) => Interpolation<Theme>
      : Interpolation<Theme>;
  }
>(
  styles: TStyles
) => styles;

扩展索引类型后,Getter的自动补全恢复正常,但普通Interpolation的补全仍失效。

困惑点

原本猜测是TypeScript泛型解析延迟的限制,但最终类型和所有类型检查都完全正确,无法理解自动补全失效的原因。已在VS Code和CodeSandbox中验证了相同行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:47:39