Skip to content

Commit 5ea4c31

Browse files
authored
Merge pull request #4143 from riqts/document-withTypes-for-2.1.0
[Docs] Added withTypes documentation in createDraftSafeSelector
2 parents 6f4194d + 621b53e commit 5ea4c31

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

docs/api/createSelector.mdx

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ hide_title: true
99

1010
# `createSelector`
1111

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

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

27-
# `createDraftSafeSelector`
29+
## `createDraftSafeSelector`
2830

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

@@ -86,3 +88,50 @@ const draftSafeSelector = createWeakMapDraftSafeSelector(
8688
```
8789

8890
:::
91+
92+
### Defining a Pre-Typed `createDraftSelector`
93+
94+
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`.
95+
96+
```ts no-transpile
97+
const createTypedDraftSafeSelector = createDraftSafeSelector.withTypes<RootState>()
98+
```
99+
100+
Import and use the pre-typed `createTypedDraftSafeSelector` function, and it will automatically know that the `state` argument is of type `RootState`.
101+
102+
:::warning Known Limitations
103+
Currently this approach only works if input selectors are provided as a single array.
104+
105+
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
106+
107+
1. Wrap your input selectors in a single array
108+
2. You can annotate the parameter types of the result function:
109+
110+
```ts no-transpile
111+
import { createSelector } from 'reselect'
112+
113+
interface Todo {
114+
id: number
115+
completed: boolean
116+
}
117+
118+
interface Alert {
119+
id: number
120+
read: boolean
121+
}
122+
123+
export interface RootState {
124+
todos: Todo[]
125+
alerts: Alert[]
126+
}
127+
128+
export const createTypedDraftSafeSelector = createDraftSafeSelector.withTypes<RootState>()
129+
130+
const selectTodoIds = createTypedDraftSafeSelector(
131+
// Type of `state` is set to `RootState`, no need to manually set the type
132+
state => state.todos,
133+
// ❌ Known limitation: Parameter types are not inferred in this scenario
134+
// so you will have to manually annotate them.
135+
(todos: Todo[]) => todos.map(({ id }) => id)
136+
)
137+
```

0 commit comments

Comments
 (0)