Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DistinctUntilChanged keyselector typing issue #5484

Open
niklas-wortmann opened this issue Jun 11, 2020 · 4 comments
Open

DistinctUntilChanged keyselector typing issue #5484

niklas-wortmann opened this issue Jun 11, 2020 · 4 comments

Comments

@niklas-wortmann
Copy link
Member

I am not entirely sure for the reason behind that so I create this issue rather than fixing it.
Calling distinctUntilChanged with an anonymous keyselector function leads to K being infered as unknown.

from([
  { name: 'Porsche', model: '911' },
  { name: 'PORSCHE', model: '911' },
  { name: 'Ferrari', model: 'F40' },
  { name: 'FERRARI', model: 'F40' },
]).pipe(
  distinctUntilChanged(
     (prevCar, nextCar) => {
       return prevCar.toLowerCase() === nextCar.toLowerCase();
     },
    (car) => car.name
  )
)

car is actually properly inferred here but for some reason, the return type of that function needs to be specified explicitly.

For reference this is the "problematic" function signature:

export function distinctUntilChanged<T, K>(compare: (x: K, y: K) => boolean, keySelector: (x: T) => K): MonoTypeOperatorFunction<T>;

It seems like the type inference is processing from left to right and there K will be defaulted to unknown in the compare function, but I am not really sure about this.

@niklas-wortmann niklas-wortmann changed the title DistinctUntilChanged typing issue DistinctUntilChanged keyselector typing issue Jun 11, 2020
@cartant
Copy link
Collaborator

cartant commented Jun 11, 2020

The weird thing is that the TypeScript integration in VS Code seems to infer the type parameters correctly:

vs-code

🙈

@cartant
Copy link
Collaborator

cartant commented Jun 11, 2020

I mean it effects errors in the code, but the pop-up box gets it right.

@cartant
Copy link
Collaborator

cartant commented Jun 12, 2020

It's a TypeScript problem; there's nothing we can/should do about it. Like you say, it's because the inference goes from left to right. If the parameters are reversed, the types are inferred correctly.

The solution/workaround is to provide an explicit type for at least one of the parameters in the first callback:

     (prevCar: string, nextCar) => {
       return prevCar.toLowerCase() === nextCar.toLowerCase();
     },

@cartant
Copy link
Collaborator

cartant commented Mar 14, 2021

Related: #5679 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants