Skip to content

Instantly share code, notes, and snippets.

@fvilante
Last active August 17, 2019 01:40
Show Gist options
  • Save fvilante/e77d52b9cc50bc8dd0ebc89507cec980 to your computer and use it in GitHub Desktop.
Save fvilante/e77d52b9cc50bc8dd0ebc89507cec980 to your computer and use it in GitHub Desktop.
Function composition
// 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'
@fvilante
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment