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

如何将TypeScript泛型类型传递给内部函数

问题描述

我正尝试实现一个抽象「模块」概念的函数,每个模块可接收预定义的输入,但在处理泛型输入时遇到了问题。

以下是最小可复现示例:

// 模块创建函数签名
const createModule = <TInput>(callback: (arg: TInput) => void) => {
    // 对callback进行一些处理
}

// 这个场景运行正常:
type ButtonInput = { onTap: () => void };
const button = createModule<ButtonInput>((config) => {
// 使用config.onTap做一些操作
// [ ... ]
})

// 有问题的场景:

// 示例泛型函数
const modalRef = <T extends Record<string, string>>() => {}

type ModalInput<T extends Record<string, string>> = { value: T };
const modal = createModule<ModalInput<T>>((config) => {
// ------------------------------ ^^^ 找不到名称 'T'。(2304)
// 我需要在回调内部访问泛型参数
const ref = modalRef<T>()
// ------ --------- ^^^ 找不到名称 'T'。(2304)
// [ ... ] 使用ref做一些操作
})
解决方案

问题核心在于当前createModule仅支持接收具体的输入类型,但你需要它兼容带泛型参数的类型(比如ModalInput<T>)。以下是两种可行的改造方案:

方案一:让createModule支持高阶泛型

将createModule设计为可接收泛型类型构造器的形式,把泛型参数的声明权下放给回调函数:

// 改造后的模块创建函数
const createModule = <TInput extends <T>(arg: T) => unknown>(
  callback: <T extends Record<string, string>>(arg: ReturnType<TInput>) => void
) => {
    // 对callback执行原有逻辑
}

// 示例泛型函数
const modalRef = <T extends Record<string, string>>() => {}

type ModalInput<T extends Record<string, string>> = { value: T };

// 现在可以正常创建泛型模块
const modal = createModule<typeof ModalInput>((config) => {
  // 直接通过config.value推导T类型,或显式声明
  const ref = modalRef<typeof config.value>()
})

方案二:直接让createModule接收泛型参数

如果仅针对ModalInput这类特定泛型场景,可以简化设计,让createModule直接接收泛型约束:

// 改造后的createModule,直接支持泛型输入参数
const createModule = <T extends Record<string, string>>(
  callback: (arg: { value: T }) => void
) => {
    // 对callback执行原有逻辑
}

// 示例泛型函数
const modalRef = <T extends Record<string, string>>() => {}

// 创建模块时,可显式指定T类型,或让TypeScript自动推导
const modal = createModule<{ username: string }>((config) => {
  const ref = modalRef<{ username: string }>()
  // 或利用类型推导:
  // const ref = modalRef<typeof config.value>()
})

关键逻辑说明

原代码报错是因为ModalInput<T>是未完成实例化的泛型类型,TypeScript无法识别未绑定的T变量。通过改造createModule,要么让它能处理泛型类型构造器,要么直接将泛型参数提升到createModule层面,从而让T在回调函数的作用域内合法可访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:30:12