1

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)
        }
    }
    
})

1 Answer 1

3

[] 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)
        }
    }
    
})

Playground Link

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: []
}

Playground Link

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I tried on my own but I modified INITIAL_VALUE using bad practice like const INITIAL_VALUE: { recipes: Recipe[] } = { recipes: [] }. Once again thanks for a cleaner solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.