Skip to content

Commit 32b0155

Browse files
authored
Merge pull request #4443 from reduxjs/adapter-ts-docs
2 parents 3927c0c + d86ec94 commit 32b0155

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

docs/usage/usage-with-typescript.md

+31-5
Original file line numberDiff line numberDiff line change
@@ -724,20 +724,46 @@ Import and use that pre-typed `createAppAsyncThunk` instead of the original, and
724724

725725
## `createEntityAdapter`
726726

727-
Typing `createEntityAdapter` only requires you to specify the entity type as the single generic argument.
727+
Usage of `createEntityAdapter` with Typescript varies based on whether your entities are normalized by an `id` property, or whether a custom `selectId` is needed.
728728

729-
The example from the `createEntityAdapter` documentation would look like this in TypeScript:
729+
If your entities are normalized by an `id` property, `createEntityAdapter` only requires you to specify the entity type as the single generic argument. For example:
730730

731731
```ts
732732
interface Book {
733-
bookId: number
733+
id: number
734734
title: string
735-
// ...
736735
}
737736

737+
// no selectId needed here, as the entity has an `id` property we can default to
738738
// highlight-next-line
739739
const booksAdapter = createEntityAdapter<Book>({
740-
selectId: (book) => book.bookId,
740+
sortComparer: (a, b) => a.title.localeCompare(b.title),
741+
})
742+
743+
const booksSlice = createSlice({
744+
name: 'books',
745+
initialState: booksAdapter.getInitialState(),
746+
reducers: {
747+
bookAdded: booksAdapter.addOne,
748+
booksReceived(state, action: PayloadAction<{ books: Book[] }>) {
749+
booksAdapter.setAll(state, action.payload.books)
750+
},
751+
},
752+
})
753+
```
754+
755+
On the other hand, if the entity needs to be normalized by a different property, we instead recommend passing a custom `selectId` function and annotating there. This allows proper inference of the ID's type, instead of having to provide it manually.
756+
757+
```ts
758+
interface Book {
759+
bookId: number
760+
title: string
761+
// ...
762+
}
763+
764+
const booksAdapter = createEntityAdapter({
765+
// highlight-next-line
766+
selectId: (book: Book) => book.bookId,
741767
sortComparer: (a, b) => a.title.localeCompare(b.title),
742768
})
743769

0 commit comments

Comments
 (0)