Last active
August 17, 2019 01:40
-
-
Save fvilante/e77d52b9cc50bc8dd0ebc89507cec980 to your computer and use it in GitHub Desktop.
Function composition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A 100% type-safe solution to compose functions in typescript | |
// tested in TS 3.5.1 | |
type Func<A, B> = (_: A) => B | |
class ComposedFn<A, B> { | |
constructor(private f: Func<A, B>) { } | |
static of = <A,B>(fn: Func<A, B>): ComposedFn<A, B> => | |
new ComposedFn(fn) | |
then = <C>(g: Func<B, C>): ComposedFn<A, C> => | |
ComposedFn.of( (x: A) => g(this.f(x)) ) | |
run = (arg: A):B => this.f(arg) | |
} | |
//alias | |
type Pipe = <A,B>(_: Func<A,B>) => ComposedFn<A,B> | |
const pipe: Pipe = f => new ComposedFn(f) | |
//use example | |
const a = (_: string):number => 2 | |
const b = (_: number): number[] => [2] | |
const c = (_: number[]): string[] => ['a'] | |
const d = (_: string[]): string => ' World!' | |
const f = pipe(a).then(b).then(c).then(d) | |
// ok -> type of 'f' is Compose<string, string> | |
const g = f.run('foo') // ok -> type of 'g' is string | |
console.log('Hello' + g) // ok-> output: 'Hello World' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a 100% type-safe way to compose functions in TS. I developed it 3 months ago when I realized that composing 'Higher order function type inference' was not type-safe. I don't know if they already solved that issue.