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

如何实现带TypeScript类型支持的参数固定高阶组件?

问题描述

我想实现一个高阶函数(HOC),它接收一个函数,将该函数的某一参数固定为特定值,返回一个仅接收原函数未被固定参数的新函数,但没法给它加上合适的TypeScript类型支持。

我尝试的代码如下:

function overideFunctionParams< OverrideProps, ReturnType, FuncProps>(
    func: (props: FuncProps & OverrideProps) => ReturnType,
    override: OverrideProps
): (props: FuncProps) => ReturnType {
    return (props: FuncProps) => func({ ...props, ...override });
}

const iTakeAB = (props: {a: string, b: string}) => console.log(props)

const newFunc = overideFunctionParams(iTakeAB, {a: "hello"})
解决方案

核心问题是原泛型无法自动推断出FuncProps是原函数参数中排除OverrideProps后的剩余属性。可以通过TypeScript的工具类型Omit和泛型约束实现精确的类型推断:

优化后的类型实现

type OmitProps<T, U> = Omit<T, keyof U>;

function overrideFunctionParams<
  T extends Record<string, unknown>,
  U extends Partial<T>,
  R
>(
  func: (props: T) => R,
  override: U
): (props: OmitProps<T, U>) => R {
  return (props) => func({ ...props, ...override } as T);
}

// 测试用例
const iTakeAB = (props: { a: string; b: string }) => console.log(props);

// 此时 newFunc 会被正确推断为 (props: { b: string }) => void
const newFunc = overrideFunctionParams(iTakeAB, { a: "hello" });
newFunc({ b: "world" }); // 正确,只需要传b参数

关键改进点

  • 用T表示原函数的完整参数类型,U表示要固定的参数子集(通过Partial<T>约束,确保U的属性都在T中存在)
  • 用OmitProps<T, U>提取原参数中排除U属性后的剩余类型,作为返回函数的参数类型
  • 类型断言as T是安全的,因为props(剩余属性)+override(固定属性)完全覆盖了T的所有属性

多参数固定支持

如果需要同时固定多个参数,这个实现同样适用:

const iTakeABC = (props: { a: string; b: string; c: number }) => console.log(props);
const newFunc2 = overrideFunctionParams(iTakeABC, { a: "hi", c: 123 });
newFunc2({ b: "test" }); // 仅需传b参数,类型推断完全正确

内容的提问来源于stack exchange,提问作者Sigurđur Jónsson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 22:22:48