Proposal: Removal of certain overloads (RFC) #54
Replies: 3 comments 6 replies
-
Would it be possible to have two separate declarations like this? export function filter<T>(pred: (value: T) => boolean): (list: T[]) => T[];
export function filter<T>(pred: (value: T) => boolean): <U extends Record<PropertyKey, T>>(obj: U) => U It would use the first if given an array, and the 2nd if given an object? |
Beta Was this translation helpful? Give feedback.
-
@lax4mike found another instance of this, see: #69 Because of how |
Beta Was this translation helpful? Give feedback.
-
@rbuckton thank you for all your feedback on DefinitelyTyped/DefinitelyTyped#68695 and suggestions. I'm pinging you here because I think you'll find this discussion quite interesting, and was hoping to solicit some feedback and recommendations from you Thanks in advanced! |
Beta Was this translation helpful? Give feedback.
-
Some overloads have particularly bad support with typescript. Let's look at
filter
for exampleThe
filter(fn)(listOrObject)
variety can be typed in 2 ways. First is the current way:The problem with this way is that typescript always chooses the last overload when you pass a function as an argument. That means that doing this
Only works if
obj.prop
returns an object and not an array. if you flip the overload order, you can only use an array and not an object.The second way to type this is in the current update MR
This does allow for either arrays or objects in the above example, however, there is a new problem:
Although
isNotNil
is generic, it collapses tounknown
. I believe this is because the type definition does calculates withT
so typescript has to choose a minimum value for it, and that value in this case isunknown
Playground example
This is contrary to if we just had this as the definition:
Where the
T
is "transferred". See this playground exampleNow the final problem, if we overload this working version with support for objects
The
T
doesn't transfer anymore again. It collapses tounknown
. (Final playground example)The Proposal
What I would like to propose is to remove the extra overloads for functions like this. The problem is that if we keep object support, we can't even use it in its most common use-case, and the array support doesn't work when the
fn
passed tofilter
is a generic.And since to use the object overload you'd have to do this anyways:
It doesn't make sense to keep the object overload
So
filter
should only have this definition:I believe that this gives the best possible support for the most common use-case, supplementing when you want to filter on an object via an inline arrow function
filter
andmap
are to 2 main culprits of this, but there are others that I am looking into as wellBeta Was this translation helpful? Give feedback.
All reactions