Skip to content

Commit 005feda

Browse files
authored
Merge pull request #4709 from reduxjs/adapter-ts-docs
2 parents 364c1cc + 92aa3b9 commit 005feda

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

docs/usage/UsageWithTypescript.md

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,38 @@ const fetchUserById = createAsyncThunk<
634634

635635
### Typing `createEntityAdapter`
636636

637-
Typing `createEntityAdapter` only requires you to specify the entity type as the single generic argument. This typically looks like:
637+
Usage of `createEntityAdapter` with Typescript varies based on whether your entities are normalized by an `id` property, or whether a custom `selectId` is needed.
638+
639+
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:
640+
641+
```ts
642+
interface Book {
643+
id: number
644+
title: string
645+
}
646+
647+
// no selectId needed here, as the entity has an `id` property we can default to
648+
// highlight-next-line
649+
const booksAdapter = createEntityAdapter<Book>({
650+
sortComparer: (a, b) => a.title.localeCompare(b.title)
651+
})
652+
653+
const booksSlice = createSlice({
654+
name: 'books',
655+
// highlight-start
656+
// The type of the state is inferred here
657+
initialState: booksAdapter.getInitialState(),
658+
// highlight-end
659+
reducers: {
660+
bookAdded: booksAdapter.addOne,
661+
booksReceived(state, action: PayloadAction<{ books: Book[] }>) {
662+
booksAdapter.setAll(state, action.payload.books)
663+
}
664+
}
665+
})
666+
```
667+
668+
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.
638669

639670
```ts
640671
interface Book {
@@ -643,8 +674,8 @@ interface Book {
643674
// ...
644675
}
645676

646-
// highlight-next-line
647677
const booksAdapter = createEntityAdapter({
678+
// highlight-next-line
648679
selectId: (book: Book) => book.bookId,
649680
sortComparer: (a, b) => a.title.localeCompare(b.title)
650681
})

0 commit comments

Comments
 (0)