2 ms·
This particular use case is trying to strongly type the "Flux Standard Action" object shape. An object _may_ have a `payload` field for its data, _may_ have an
by acemarke 4y ago
This particular use case is trying to strongly type the "Flux Standard Action" object shape. An object _may_ have a `payload` field for its data, _may_ have an `error` field that indicates this action represents an error, and _may_ have a `meta` field that provides additional descriptive information.
This isn't part of the Redux core package, but it's a convention the community adopted shortly after Redux became popular. Redux Toolkit uses that as the standard structure for an action object. `createAction` defaults to just `{type, payload}`, but you can optionally provide a callback that adds the other `meta` and `error` fields. So yes, there's some additional complexity here because of the optional field contents, and this type is telling TS what the final type should look like based on which fields exist.
Note that as an end user, you normally don't even call `createAction` yourself - it's automatically called as part of our `createSlice` API. What end users normally write is:
export const counterSlice = createSlice({
name: 'counter',
// `createSlice` will infer the state type from the `initialState` argument
initialState,
reducers: {
increment: state => {
state.value += 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
// `action.payload` is now a `number`
state.value += action.payload
}
}
})