Last active
September 19, 2021 02:40
-
-
Save sushruth/b6cedc3a8af86ba13d822ab4f077bf14 to your computer and use it in GitHub Desktop.
Type safe pipe operator equivalent
This file contains 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
class Pipeable<I> { | |
constructor(public value: I) { } | |
public pipe<O>(fn: (input: I) => O) { | |
const output = fn(this.value); | |
return Object.assign(new Pipeable(output).pipe, { | |
value: output | |
}); | |
} | |
} | |
export function pipe<T>(input: T) { | |
return new Pipeable(input).pipe | |
} |
This file contains 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
const result = pipe(2) | |
(v => v * v) | |
(v => v.toString()) | |
(v => v.toUpperCase()) | |
.value // result is now string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment