Definitelytyped: [@types/lodash] Lacking type inference after chaining

Created on 11 May 2019  路  8Comments  路  Source: DefinitelyTyped/DefinitelyTyped

const x = _.chain([1]).value();

Type of x is ArrayLike<number>. But it should be number[];

/cc @aj-r

Most helpful comment

This change would require me to make changes to several dozen .chains that are expected to return T[], but now are typed as ArrayLike<T>. I would consider the change that caused this to be a "breaking" change.

All 8 comments

This change was made as part of an effort to improve the performance of the lodash types. If this is a big problem then we can try to find a solution, but it may not be straightforward. What issue is this causing?

cc @sandersn

e.g.

function someFunction(): string[] {
    return _.chain(['A', 'B', 'C']).map((letter) => letter.toLowerCase()).value();
}

I'm also having issues with the new typing since 4.14.125.

When lodash is returning an ArrayLike<number> which you assign to a number[] you get the error:

Type 'ArrayLike<number>' is missing the following properties from type 'number[]': pop, push, concat, join, and 25 more.

@sandersn I wonder if we should add a new chain type for arrays - it could inherit from Collection<T> but value() would return T[] instead of ArrayLike<T>.

Or possibly modify Collection<T>.value() to return T[], even though that's not technically correct all of the time, it's probably correct 99% of the time.

_.chain({ 0: 1, length: 1 }).map(_.id).value() // [1]
_.chain({ 0: 1, length: 1 }).filter(Boolean).value() // [1]
_.chain({ 0: 1, length: 1 }).sort().value() // {0: 1, length: 1}
_.chain({ 0: 1, length: 1 }).value() // {0: 1, length: 1}

@sandersn I wonder if we should add a new chain type for arrays - it could inherit from Collection<T> but value() would return T[] instead of ArrayLike<T>.

Or possibly modify Collection<T>.value() to return T[], even though that's not technically correct all of the time, it's probably correct 99% of the time.

We have to manually type cast to solve this now, so that kind of change sounds like less casting to me! Ship it!

This change would require me to make changes to several dozen .chains that are expected to return T[], but now are typed as ArrayLike<T>. I would consider the change that caused this to be a "breaking" change.

@aj-r We could add Array (or some similar name) but I don't think subtyping would work. We'll have to duplicate all the Collection functions over to Array.

Might be better just to optimistically return Array.

Was this page helpful?
0 / 5 - 0 ratings