Skip to content

Instantly share code, notes, and snippets.

@casesandberg
Created August 11, 2019 02:21
Show Gist options
  • Save casesandberg/92f19b7176b5190b2cfcc264ea8dd2f0 to your computer and use it in GitHub Desktop.
Save casesandberg/92f19b7176b5190b2cfcc264ea8dd2f0 to your computer and use it in GitHub Desktop.
Seems like I am doing a lot of boilerplate here for TypeScript, any suggestions on making it more concise?
// This is how I would traditionally do it
export const selector = 'toasts'
export const actionTypes = {
ADD: `${selector}/ADD`,
SHOW: `${selector}/SHOW`,
HIDE: `${selector}/HIDE`,
}
export const reducer = (state = {}, action) => {
switch (action.type) {
case SHOW: {
return {
...state,
[action.id]: {
message: action.message,
}
}
}
case HIDE: {
const newState: State = { ...state }
delete newState[action.id]
return newState
}
default:
return state
}
}
export const actions = {
add: ({ message }) => ({
type: ADD,
message,
}),
show: ({ id, message }) => ({
type: SHOW,
id,
message,
}),
hide: ({ id }) => ({
type: HIDE,
id,
}),
}
export const selectors = {
get: ({ state }) => state[selector]
}
export const selector = 'toasts'
// Typescript doesnt like when we auto-generate these with `${selector}/ACTION`
const ADD = `toasts/ADD`
const SHOW = `toasts/SHOW`
const HIDE = `toasts/HIDE`
export const actionTypes: any = {
ADD,
SHOW,
HIDE,
}
interface State {
[id: string]: {
message: string,
}
}
const initialState: State = {}
export const reducer = (state: State = initialState, action: Actions) => {
switch (action.type) {
case SHOW: {
return {
...state,
[action.id]: {
message: action.message,
}
}
}
case HIDE: {
const newState: State = { ...state }
delete newState[action.id]
return newState
}
default:
return state
}
}
export type Actions = ShowAction | HideAction | AddAction
export interface AddActionParams {
message: string;
}
export type AddAction = AddActionParams & {
type: typeof ADD,
}
export interface ShowActionParams {
id: string;
message: string;
}
export type ShowAction = ShowActionParams & {
type: typeof SHOW,
}
export interface HideActionParams {
id: string;
}
export type HideAction = HideActionParams & {
type: typeof HIDE,
}
export const actions = {
add: ({ message }: AddActionParams): AddAction => ({
type: ADD,
message,
}),
show: ({ id, message }: ShowActionParams): ShowAction => ({
type: SHOW,
id,
message,
}),
hide: ({ id }: HideActionParams): HideAction => ({
type: HIDE,
id,
}),
}
export const selectors = {
get: ({ state }: any) => state[selector]
}
@Jarred-Sumner
Copy link

export const actionTypes = {
  ADD: `${selector}/ADD`,
  SHOW: `${selector}/SHOW`,
  HIDE: `${selector}/HIDE`,
}

you could use an enum instead

export enum ReduxActionType {
 add = "toasts/add",
 show = "toasts/show",
 remove = "toasts/remove",
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment