Pipe/flow/chain type support
See original GitHub issueSearch Terms
recursive, flow, pipe, chain
Suggestion
I do not have a specific implementation in mind to support this. There is a decent existing solution by a stackoverflow user @jcalz, which does its best given what typescript is able to accomplish now. I have created this issue to more to specifically point out the current limitation of typescript in regard to this feature, and the current use cases. This feature request falls under the larger umbrella of recursive type inference.
At its most broad, I would like to suggest that typescript include some form of an official Chain
type that developers can use.
Unanswered Questions
- should this type have an official implementation with a max recursion value?
pipe: Chain<In, Out, number>
- will this design pattern cease to be relevant if the tc39 pipeline proposal is integrated into javascript?
Use Cases
There are a number of implementations for javascript pipes in common libraries.
Related Issues
https://github.com/Microsoft/TypeScript/issues/27102 https://github.com/Microsoft/TypeScript/issues/28505
Examples
a typical implementation looks like this:
function pipe<T, A>(arg1: (in: T) => A): A
function pipe<T, A, B>(arg1: (in: T) => A, arg2: (in: A) => B): (in: T) => B
function pipe(...args: any[]): (in: any) => any
const strToNumber = (str: string) => parseInt(str)
const add = (x: number) => (y: number) => x + y
const safeAdder = pipe(strToNumber, add(5))
const out: number = safeAdder('6') // returns 11
The limitation of the current implementation is that if you use a typed pipe function with more arguments than the written overloads, you run lose type inference.
Checklist
My suggestion meets these guidelines:
- This wouldn’t be a breaking change in existing TypeScript/JavaScript code
- This wouldn’t change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn’t a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript’s Design Goals.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:15
- Comments:11
Top GitHub Comments
I managed to implement a pipe function type. Instead of overloading, it uses tuple rest args and recursion.
There are 2 flavors of the pipe type. One returns a function (
Pipe
), and the other has a value as the first argument and immediately executes (PipeValue
).It correctly identifies the first incorrect argument.
The return type of the pipe function is correctly inferred even if there are incorrect arguments.
For compose, just switch around the inferring of A and R
I’ve made an updated version which:
Playground
Code
Examples