能否在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
相关产品推荐
相关产品推荐

