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

能否在TypeScript中重载泛型参数实现类似C#的Action/Func类型?

TypeScript中实现C#风格无数字后缀的Action/Func泛型类型

我是C#开发出身,C#里的委托类型定义如下:

Action        // 无返回值的方法
Action<T1>    // 带一个T1类型参数的无返回值方法
Action<T1,T2> // 带T1、T2两个参数的无返回值方法
Func<T1>      // 返回T1类型的无参方法
Func<T1,T2>   // 带一个T1类型参数、返回T2类型的方法

我认为function Koala(func1:Action, func2:Func<string,number>)这种写法,比function Koala(func1:()=>void, func2:(value1:string)=>number)的可读性强很多——后端已经采用前者的风格,团队理解起来更顺畅。

目前我在TypeScript里是通过带数字后缀的类型定义来实现类似功能的:

type Action = ()=>void;
type Action1<T1> = (a:T1)=>void;
type Action2<T1,T2> = (a:T1,b:T2)=>void;
type Action3<T1,T2,T3> = (a:T1,b:T2,c:T3)=>void;

type Func<T1> = ()=>T1;
type Func1<T1,T2> = (a:T1)=>T2;
type Func2<T1,T2,T3> = (a:T1,b:T2)=>T3;

var cheese:Func1<string,boolean>;

let value = cheese('test');

但我不想使用数字后缀,能不能通过重载泛型参数,让Action<string,bool>自动匹配对应的带两个参数的无返回值方法类型?请问这种实现方式可行吗?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:04:55