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

TypeScript泛型实现ThunkAction剩余参数类型校验

Thunk Action剩余参数的泛型类型校验方案

问题背景

定义了可接收任意参数的TThunkAction类型,但调用时传入不匹配参数不会触发TypeScript类型警告。已实现单对象参数的泛型版本,希望通过剩余参数形式实现强类型校验。

原代码(无类型校验)

type TThunkAction = (...payload: any) => (dispatch: () => void) => void

const action: TThunkAction = (id: number, text: string) => (dispatch) => {}
action('123', false) // 无类型警告,不符合预期

单对象参数的泛型实现(已完成)

type TThunkAction<TPayload = any> = (payload?: TPayload) => (dispatch: () => void) => void

const action: TThunkAction<{id: number, text: string}> = ({id, text}) => (dispatch) => {}
action({id: 123, text: "test"}) // 强类型校验生效

剩余参数形式的泛型解决方案

通过元组泛型约束剩余参数的类型,实现调用时的强校验:

// 泛型参数约束为任意元组类型,默认值为any[]保持兼容性
type TThunkAction<TArgs extends any[] = any[]> = (...payload: TArgs) => (dispatch: () => void) => void

// 声明action时传入具体的参数元组类型
const action: TThunkAction<[number, string]> = (id: number, text: string) => (dispatch) => {}

// 合法调用:参数类型匹配
action(123, "hello")

// 非法调用:TypeScript会直接抛出类型错误
action('123', false) // 类型不匹配,TS报错

方案说明

  • 将泛型参数TArgs约束为元组类型TArgs extends any[],可精准定义剩余参数的数量和每个参数的类型
  • 声明action时传入具体元组(如[number, string]),TS会自动校验调用时的参数是否与元组类型匹配
  • 默认值any[]保留了原类型的兼容性,无需强校验的场景仍可直接使用TThunkAction

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:25:59