gpt4 book ai didi

javascript - 是否可以对 Redux Toolkit Slice 的状态使用 typescript 联合类型?

转载 作者:行者123 更新时间:2023-12-02 18:11:53 32 4
gpt4 key购买 nike

在使用 Redux Toolkit 时,我想使用这样的联合类型来表示切片的状态:

type AppState = { loading: true } | { loading: false; data: number };

似乎在 reducer 文件中使用 Immerjs 使我无法在两个 Union 选项之间切换,例如:

import { createSlice, PayloadAction } from "@reduxjs/toolkit";

const initialState: AppState = { loading: true };

export const sampleSlice = createSlice({
name: "sample",
initialState,
reducers: {
setup: (state) => {
return { loading: false, data: 5 };
},
},
});

这给了我以下 Typescript 错误:

Type '(state: WritableDraft<{ loading: true; }>) => { loading: false; data: number; }' is not assignable to type 'CaseReducer<{ loading: true; }, { payload: any; type: string; }> | CaseReducerWithPrepare<{ loading: true; }, PayloadAction<any, string, any, any>>'.

有什么办法可以实现吗?我当前的解决方法不是使用联合类型来表示状态,但我想知道是否有解决方法。我也尝试过不使用 bool 值,而是为 loading 键使用字符串文字,但它会产生相同的错误。

最佳答案

注意:根据文档,选项 2 是更好的方法。

选项 1。为 createSlice 提供通用参数类型。

import { createSlice, SliceCaseReducers } from '@reduxjs/toolkit';

type AppState = { loading: true } | { loading: false; data: number };

const initialState: AppState = { loading: true };

type CaseReducers = SliceCaseReducers<AppState>;

export const sampleSlice = createSlice<AppState, CaseReducers>({
name: 'sample',
initialState,
reducers: {
setup: (state) => {
return { loading: false, data: 5 };
},
},
});

在 case reducer 中的state 类型:

enter image description here

选项 2. 转换初始状态。参见 Defining the Initial State Type

import { createSlice, SliceCaseReducers } from '@reduxjs/toolkit';

type AppState = { loading: true } | { loading: false; data: number };

const initialState: AppState = { loading: true };

// type CaseReducers = SliceCaseReducers<AppState>;

export const sampleSlice = createSlice({
name: 'sample',
initialState: initialState as AppState,
reducers: {
setup: (state) => {
return { loading: false, data: 5 };
},
},
});

包版本:

"@reduxjs/toolkit": "^1.6.1",
"typescript": "^4.3.5",

关于javascript - 是否可以对 Redux Toolkit Slice 的状态使用 typescript 联合类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72185233/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com