Skip to content

RFC: Type pinning and partial inference for reateAsyncThunks #1986

Closed
@garronej

Description

@garronej

Hello @markerikson and @phryneas,

This proposal suggests that typescript users may get the createAsyncThunks function via a factory to improve DX and code readability.

Benefits

  • It encapsulates the AsyncThunkConfig, users get a createAsyncThunk function specific for their store.
  • Users only have to explicitly provide the type annotations that can't be inferred, namely
    • The argument of the thunk.
    • (Optionally) specific expected type for rejectValue, serializedErrorType , pendingMeta, fulfilledMeta and rejectedMeta.
  • It couples the name of the function and the last portion of the typePrefix. (It relies on template literal types)

Playground

Code sandbox link

  • counter_vanilla.ts: State of the art with the regular createAsyncThunks.
  • counter.ts: Use of the alternative createAsyncThuks that is the object of this proposal.
  • setup.ts: Where createStore() is supposed to be called.
  • createAsyncThunks.ts: File that export the createAsyncThuks returned by our factory function.
  • RTK-ext.ts: Implementation of the factory function.
Screen.Recording.2022-02-02.at.00.41.29.mov

Drawbacks

  • Users must call the factory function in a different file than the one where createStore() is called or they will get require
    cycles. They should also use import type to import their AsyncThunkConfig type.
  • Template literal types aren't backward compatible. This utility, as it is, couldn't be indexed. It would have to be available under @redux/toolkit/factories for example.
  • Having to provide an extra () is what unlocks partial argument inference but it will look a bit weird, especially to vanilla JavaScript users. That said, JavaScript users wouldn't have to know about this factory. They could keep using the createAsyncThunks exported from @redux/toolkit as they would see no benefit using the factory.

Available implementation

createAsyncThunksFactory is already available in redux-clean-architecture and here is an example DIFF induced by using this proposal.


We started from the wrong foot on reddit I would understand if you are not interested in me contributing any further but I you are interested I can come up with a PR.

Best regards,

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions