[Typescript] Typing a Function Composition with Overloads and Generics
import { expect, it } from 'vitest';
import { Equal, Expect } from '../helpers/type-utils';
export function compose<T1, T2>(func: (t1: T1) => T2): (t1: T1) => T2;
export function compose<T1, T2, T3>(
func1: (t1: T1) => T2,
func2: (t2: T2) => T3
): (t1: T1) => T3;
export function compose<T1, T2, T3, T4>(
func1: (t1: T1) => T2,
func2: (t2: T2) => T3,
func3: (t3: T3) => T4
): (t1: T1) => T4;
export function compose<T1, T2, T3, T4, T5>(
func1: (t1: T1) => T2,
func2: (t2: T2) => T3,
func3: (t3: T3) => T4,
func4: (t3: T4) => T5
): (t1: T1) => T5;
export function compose(...funcs: Array<(input: any) => any>) {
return (input: any) => {
return funcs.reduce((acc, fn) => fn(acc), input);
};
}
const addOne = (num: number) => {
return num + 1;
};
const addTwoAndStringify = compose(addOne, addOne, addOne, String);
it('Should compose multiple functions together', () => {
const result = addTwoAndStringify(4);
expect(result).toEqual('7');
type tests = [Expect<Equal<typeof result, string>>];
});
it('Should error when the input to a function is not typed correctly', () => {
const stringifyThenAddOne = compose(
// addOne takes in a number - so it shouldn't be allowed after
// a function that returns a string!
// @ts-expect-error
String,
addOne
);
});
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-03-02 [SCSS] SCSS and CSS Variables
2020-03-02 [Github] Create a GitHub PR Template
2020-03-02 [Github] Create a GitHub Issue Template
2017-03-02 [SVG] Combine Multiple SVGs into an SVG Sprite
2017-03-02 [Ramda] Difference between R.converge and R.useWith
2017-03-02 [Ramda] Refactor to a Point Free Function with Ramda's useWith Function
2017-03-02 [Angular] Dynamic component's instance and sorting