Web Development
TypeScript
Subjective
Oct 04, 2025
How do you implement type-safe function composition in TypeScript?
Detailed Explanation
Type-safe function composition ensures input and output type compatibility.
Basic composition function:
function compose(f: (b: B) => C, g: (a: A) => B): (a: A) => C {
return (a: A) => f(g(a));
}
Example usage:
const addOne = (x: number) => x + 1;
const toString = (x: number) => x.toString();
const composed = compose(toString, addOne);
Pipe implementation:
function pipe(value: T, ...fns: Function[]): any {
return fns.reduce((acc, fn) => fn(acc), value);
}
const result = pipe(5, addOne, toString);
Benefits: Type safety, function reusability, clear data flow.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts