简体   繁体   English

Typescript 和 redux 工具包

[英]Typescript and redux toolkit

How can I make an array of Recipe type in Initialvalue, and how to make Payloadaction as a object type?如何在 Initialvalue 中创建一个 Recipe 类型的数组,以及如何将 Payloadaction 设置为 object 类型? I am a typescript beginner unfortunetly.不幸的是,我是 typescript 初学者。

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. []将是一个never数组,因为没有关于数组中元素类型的任何信息。 The simplest thing you could do is assert [] to be Recipe[]您可以做的最简单的事情是将[]断言为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:您还可以为INITIAL_VALUE提供显式类型注释,但这需要您为所有属性执行此操作,并且需要您在两个位置定义属性:

const INITIAL_VALUE: {
    recipes: Recipe[]
} = {
    recipes: []
}

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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