如何在 Redux-toolkit 的 Initialstate 中定义类型?

How can I define a type in Initialstate in Redux-toolkit?

我想为切片状态中的初始值定义一个类型。但是我不知道怎么办。

如果我在 singlePost 中输入 null,我会收到这条红线警告。

但是我想指定singlePost初始值的类型

singlePost 将包含这些值。

这是我的代码

    // singlePost = {
    //   Comments: [
    //      {id: 46, content: "hello", createdAt: "2022-04-30T08:24:15.000Z", 
    //   }
    //   {id: 47, content: "zz", createdAt: "2022-04-30T08:24:30.000Z",
    // ],

    // Images: [
    //   PostId: 61
    //   createdAt: "2022-04-27T08:17:51.000Z"
    //   id: 6
    //   src: "bd8b355e-cfe8-4c50-be4c-6c4958958fc6.JPEG"
    //   updatedAt: "2022-04-27T08:17:51.000Z"]

    //   Likecomments: [{},{}]

    //   Likers: [{}]

    //   User:{id:2, nickname:'elon'}

    //   content:"helloword"

    //   createdAt:"22022-212"

    //   id: 61,

    //   updatedAt:"asdasd"
    // }


    export const initialState = {

      singlePost: null,

    }
    const postSlice = createSlice({
      name: 'post',
      initialState,
      reducers: {},
      extraReducers: builder =>
        builder

          .addCase(addComment.fulfilled, (state, action: PayloadAction<test>) => {

            const post = state.mainPosts.find(v => v.id === action.payload.PostId);

            state.addCommentLoading = false;
            state.addCommentDone = true;
            state.singlePost.Comments.push(action.payload);
            post.Comments.push(action.payload);
          })

          .addDefaultCase(state => state),
    });

例子很多in the docs for createSlice

你需要一个界面

interface MySliceState {
  singlePost: null | {
    Comments: Array<{
      id: number,
      content: string,
      ...
    }>,
    Images: ...,
    ...
  }
}

然后断言 inialState 是那种类型。

    const initialState = {

      singlePost: null,

    } as MySliceState 
interface IImage {
  PostId: number;
  createdAt: string;
  id: number;
  //....
}

interface IComment {
  id: number;
  content: string;
  createdAt: string;
}

inteface ISinglePost {
    Comments: IComment[] | null;
    Images?: IImage[];
}

interface IInitialState {
  singlePost: ISinglePost | null;
}

export const initialState: IInitialState = {

  singlePost: null,

}