Skip to main content

Redux Toolkit 的 JSDoc 型別註記 - action 和 thunk

Thunk

payloadCreator 的函數上面進行 JSDoc 的標註,即可有型別提示

import { createAsyncThunk } from '@reduxjs/toolkit'

export const patchUser = createAsyncThunk(
`myReducer/patchUser`,

/**
* @typedef {Object} PatchUserPayload
* @property {string} userId
* @property {string} name
* @property {string} email
*/

/**
* @param {PatchUserPayload} payload
*/
async ({ userId, name, email }, { getState }) => {}
)

型別提示的時候會告知參數使用 PatchUserPayload

如果在 dispatch thunk 的元件裡面開啟 //@ts-check,若 payload 結構錯誤也會進行提醒

Reducer

import { createSlice } from '@reduxjs/toolkit'

export const mySlice = createSlice({
name: 'myReducer',
initialState: {},
reducers: {
/**
* @typedef {Object} OpenEditorPayload
* @property {string} postId
* @property {string} postType
* @property {string} postName
* @property {string} postText
*/

/**
* @param {import("@reduxjs/toolkit").PayloadAction<OpenEditorPayload>} action
*/
openEditor: (state, action) => {
// 略
},
},
extraReducers: (builder) => {},
})

引入 import("@reduxjs/toolkit").PayloadAction<OpenEditorPayload>,對 action 進行註記

JSDoc 可以沿用 TS 的泛型真的頗神奇的