Skip to content

Commit

Permalink
Merge pull request #4143 from riqts/document-withTypes-for-2.1.0
Browse files Browse the repository at this point in the history
[Docs] Added withTypes documentation in createDraftSafeSelector
  • Loading branch information
EskiMojo14 committed Feb 12, 2024
2 parents 6f4194d + 621b53e commit 5ea4c31
Showing 1 changed file with 50 additions and 1 deletion.
51 changes: 50 additions & 1 deletion docs/api/createSelector.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ hide_title: true

# `createSelector`

## Overview

The `createSelector` utility from the [Reselect library](https://github.com/reduxjs/reselect), re-exported for ease of use.

For more details on using `createSelector`, see:
Expand All @@ -24,7 +26,7 @@ allowed using string keypaths as input selectors. This was removed, as it ultima
the string keypaths made static typing for selectors difficult.
:::

# `createDraftSafeSelector`
## `createDraftSafeSelector`

In general, we recommend against using selectors inside of reducers:

Expand Down Expand Up @@ -86,3 +88,50 @@ const draftSafeSelector = createWeakMapDraftSafeSelector(
```

:::

### Defining a Pre-Typed `createDraftSelector`

As of RTK 2.1, you can define a "pre-typed" version of `createDraftSafeSelector` that can have the type for `state` built in. This lets you set up those types once, so you don't have to repeat them each time you call `createDraftSafeSelector`.

```ts no-transpile
const createTypedDraftSafeSelector = createDraftSafeSelector.withTypes<RootState>()
```

Import and use the pre-typed `createTypedDraftSafeSelector` function, and it will automatically know that the `state` argument is of type `RootState`.

:::warning Known Limitations
Currently this approach only works if input selectors are provided as a single array.

If you pass the input selectors as separate inline arguments, the parameter types of the result function will not be inferred. As a workaround you can either

1. Wrap your input selectors in a single array
2. You can annotate the parameter types of the result function:

```ts no-transpile
import { createSelector } from 'reselect'

interface Todo {
id: number
completed: boolean
}

interface Alert {
id: number
read: boolean
}

export interface RootState {
todos: Todo[]
alerts: Alert[]
}

export const createTypedDraftSafeSelector = createDraftSafeSelector.withTypes<RootState>()

const selectTodoIds = createTypedDraftSafeSelector(
// Type of `state` is set to `RootState`, no need to manually set the type
state => state.todos,
// ❌ Known limitation: Parameter types are not inferred in this scenario
// so you will have to manually annotate them.
(todos: Todo[]) => todos.map(({ id }) => id)
)
```

0 comments on commit 5ea4c31

Please sign in to comment.