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

TypeScript约束const函数返回值时如何保留其原始参数类型

问题根因

当你直接给函数变量显式标注Fn类型时,TypeScript会将该变量的类型直接收敛为标注的Fn类型,赋值时传入的实际函数的参数类型会被丢弃,因此调用Parameters取到的永远是Fn定义里的any[],拿不到每个函数实际的入参类型。

实现方案

通过泛型辅助函数做类型约束即可,既能强制所有函数返回固定的[string, number]格式,又能完整保留每个函数自身的入参类型:

type ReturnFormat = [string, number]

// 泛型辅助函数,仅做类型校验,无额外运行逻辑
const defineFn = <T extends (...args: any[]) => ReturnFormat>(fn: T) => fn

// 定义符合要求的函数,不需要手动标注类型
const A = defineFn(() => ['one', 1])
const B = defineFn((input: number) => ['two', input])

// 读取参数类型可得到正确结果
type C = Parameters<typeof A> // 类型为 [],对应无入参
type D = Parameters<typeof B> // 类型为 [input: number]

校验效果说明

  • 如果定义的函数返回值不符合[string, number]格式,TypeScript会直接抛出类型错误,满足强制返回格式的要求
  • 每个函数的入参类型会被完整保留,不会被统一擦除为any[],后续读取参数、返回值类型都能拿到精准结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 14:54:22