Skip to content

Why does TypeScript not infer types for some piped functions? #22051

Closed
@ivan7237d

Description

@ivan7237d

This is a question rather than a bug report or a feature request, but I've tried asking this on stackoverflow and gitter with no success, so maybe I'll have more luck here.

In the following code snippet, if you look at the last two lines, TypeScript shows an error in the first one, and correctly infers types in the second one, although the difference is only the order in which the functions are piped.

const pipe = <A, B, C>(
  x: A,
  a: (x: A) => B, 
  b: (x: B) => C,
) => b(a(x));

// This just calls the function passed as argument.
const call = <A, B>(f: (x: A) => B) => (x: A) => f(x)

const a = pipe(1, x => x + 1, call(x => x + 1));
const b = pipe(1, call(x => x + 1), x => x + 1);

I use TypeScript 2.7.1 in the strict mode (including strictFunctionTypes), however the strict mode doesn't seem to matter here. Here is this snippet on TypeScript playground.

It is a problem that I often run into when working with RxJS, since in RxJS there is a similar pipe method and I pass arrow functions to it when using creation operators (like obs => merge(obs, otherObs)). Usually it's easy to work around this problem by specifying the argument type, but I would like to understand the logic behind this. Why is TypeScript able to infer the type in one case but not in the other?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions