简体   繁体   中英

Typescript and redux toolkit

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM