Skip to content

Typescript does not implicitly infers types when providing function as arguments? #17520

Closed
@1ven

Description

@1ven

When providing identity function to map, it's return type is incorrect(see x2), while providing anonymous function as a callback leads to a correct output type(see x1).

TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)

Code

const map = <T, U>(f: (x: T) => U, arr: T[]): U[] => {
  return arr.map((val) => f(val));
}

// x1 type is number[]
const x1 = map(x => x, [1, 2, 3]);

const identity = <T>(x: T) => x
// x2 type is {}[]
const x2 = map(identity, [1, 2, 3]);

Expected behavior:
Return type of map function, when providing identity function should be number[]

Actual behavior:
Return type is {}[]


Also, I've realized that map function in 2nd example does not infers even T type. It's {} currently, while it's obvious should be a number type, as we are providing array of numbers:
screen shot 2017-07-30 at 11 47 52 pm

The second interesting thing is, that type inferring works fine, if map function arguments will be reversed:

const map = <T, U>(arr: T[], f: (x: T) => U): U[] => {
  return arr.map((val) => f(val));
}
// x2 type is number[]
const x2 = map1([1, 2, 3], identity);

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions