Reputation: 881
How can I make an array of Recipe type in Initialvalue, and how to make Payloadaction as a object type? I am a typescript beginner unfortunetly.
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
type Recipe = {
title: string,
}
const INITIAL_VALUE = {
recipes: []
}
const recipeSlice = createSlice({
name: 'recipe',
initialState: INITIAL_VALUE,
reducers: {
addRecipe(state, action: PayloadAction<{}>) {
state.recipes.push(action.payload)
}
}
})
Upvotes: 1
Views: 106
Reputation: 249636
[]
will be an array of never
since there isn't any information about the type of an element in the array. The simplest thing you could do is assert []
to be Recipe[]
const INITIAL_VALUE = {
recipes: [] as Recipe[]
}
const recipeSlice = createSlice({
name: 'recipe',
initialState: INITIAL_VALUE,
reducers: {
addRecipe(state, action: PayloadAction<Recipe>) {
state.recipes.push(action.payload)
}
}
})
You could also provide an explicit type annotation for INITIAL_VALUE
but that will require you do it for all properties and will require you define the properties in two places:
const INITIAL_VALUE: {
recipes: Recipe[]
} = {
recipes: []
}
Upvotes: 3