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

TypeScript回调返回函数:如何为styleCallback传递Options类型

解决TypeScript泛型传递options类型的问题

我来帮你搞定这个泛型问题!你之前的问题出在泛型的定义位置——你把<T>放在了返回的内层函数上,但实际上这个泛型需要关联外层传入的styleCallback和返回函数的options参数,所以得把泛型定义在makeStyle这个外层函数本身上。

正确的实现代码

首先假设你已经有Theme类型和getTheme函数的定义,我们来修正makeStyle:

// 示例Theme类型(根据你的实际结构调整)
type Theme = {
  primaryColor: string;
  spacing: { sm: number; md: number };
};

// 示例getTheme函数
const getTheme = (): Theme => {
  return {
    primaryColor: "#2563eb",
    spacing: { sm: 4, md: 8 }
  };
};

// 修正后的makeStyle,泛型<T>定义在外层函数上
const makeStyle = <T>(styleCallback: (theme: Theme, props: T) => any) => {
  return (options: T) => {
    const theme = getTheme(); // 别忘了加const声明变量
    return styleCallback(theme, options);
  };
};

用法示例

现在TypeScript可以自动推断options的类型,或者你也可以显式指定泛型:

自动推断类型

// 定义样式回调时,TypeScript会根据第二个参数自动推断T的类型
const cardStyle = makeStyle((theme, options) => {
  // options会被推断为{ padding: number, isHighlighted: boolean }
  return {
    padding: `${options.padding}px`,
    backgroundColor: options.isHighlighted ? "#fef3c7" : "#fff",
    borderColor: theme.primaryColor
  };
});

// 调用时会自动校验参数类型
const myCardStyles = cardStyle({ padding: theme.spacing.md, isHighlighted: true });

显式指定泛型类型

如果需要提前定义options的类型,也可以显式传入泛型参数:

// 提前定义options类型
type ButtonOptions = {
  size: "sm" | "md" | "lg";
  disabled: boolean;
};

// 显式指定<T>为ButtonOptions
const buttonStyle = makeStyle<ButtonOptions>((theme, options) => {
  return {
    padding: options.size === "sm" ? `${theme.spacing.sm}px ${theme.spacing.md}px` : 
             options.size === "md" ? `${theme.spacing.md}px ${theme.spacing.md * 2}px` : 
             `${theme.spacing.md * 1.5}px ${theme.spacing.md * 3}px`,
    opacity: options.disabled ? 0.6 : 1,
    backgroundColor: theme.primaryColor
  };
});

关键要点

  • 泛型<T>必须定义在外层的makeStyle函数上,这样它能同时约束传入的styleCallback的第二个参数,以及返回函数的options参数
  • 这样就能保证options的类型和styleCallback期望的参数类型完全一致,不会出现类型不匹配的问题
  • TypeScript会自动根据styleCallback的参数推断T的类型,无需手动指定(除非你需要提前明确类型)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 16:02:34