rxjs icon indicating copy to clipboard operation
rxjs copied to clipboard

feat: add generic type parameter to using for the resource

Open jennings opened this issue 4 years ago • 6 comments

This overload alleviates the observableFactory from needing to cast its parameter to a more specific type.

Description:

Previously, a TypeScript user has to cast the resource to the appropriate type in order to do anything with it:

const o: Observable<MyResource> = using(
  () => new MyResource(),
  r => of(r as MyResource)   // t is `Unsubscribable | void`, so a cast is needed
)

Adding a type parameter for the resource lets TypeScript infer the type of r more precisely.

I asked in discussion about this and there didn't seem to be a good reason not to implement it.

BREAKING CHANGE (maybe): @cartant suggested this might be a breaking change. There's no functionality change, but there's a worry that it will cause existing code to no longer type-check. The existing signature is in place, so I think at worst it will remove the void from the first parameter's type. That doesn't seem breaking to me, but the maintainers here have definitely seen more weird cases than I have.

Related issue (if exists):

jennings avatar Jul 02 '21 15:07 jennings

You'll need to run npm run api_guardian:update and commit the new golden files to fix the CI errors.

benlesh avatar Aug 13 '21 00:08 benlesh

@benlesh Thanks, I added that to my commit and pushed.

jennings avatar Aug 14 '21 00:08 jennings

@jennings So sorry this is such a late response. I don't have a way to force the checks to rerun without getting into your branch and pushing up an empty commit or something. Github isn't letting me approve the checks to be run. If you can, please rebase and push again so I can approve the checks to be run. Otherwise, I guess we can open a new PR with this work.

benlesh avatar Jan 11 '22 14:01 benlesh

If you can, please rebase and push again so I can approve the checks to be run.

@benlesh Done.

jennings avatar Jan 17 '22 17:01 jennings

Quoting @cartant from https://github.com/ReactiveX/rxjs/discussions/6497#discussioncomment-935487:

I suspect that using received close to no attention because it's not something that's used (pardon the pun) much.

I am one of the few users that use using from time to time and I have stumbled upon this problem several times. I'd love to see @jennings' changes implemented 🙂

sgoll avatar Aug 25 '22 14:08 sgoll

I've encountered this as well. My workaround is to add this typings file to my project

// src/@types/rxjs-using.d.ts

import type { Observable, ObservableInput, ObservedValueOf, Unsubscribable } from "rxjs"

declare module "rxjs" {
  // fix type declaration of using.
  export function using<T extends ObservableInput<any>, R extends Unsubscribable | void>(
    resourceFactory: () => R,
    observableFactory: (resource: R) => T | void
  ): Observable<ObservedValueOf<T>>
}

bman654 avatar Jul 26 '23 13:07 bman654