Building this reducer with typescript and are trying to combine a lot of types together to archive something ala this typescript mockup:
type/interface DishOrderState {
id: string
withoutIngredients: string[]
[key: string]: string
initialState: {
id: string
withoutIngredients: string[]
[key: string]: string
}
}
a state
could look like this
{
id: '123'
withoutIngredients: ['tomato'],
["BASE"]: 'rice',
initialState: {
id: '123'
withoutIngredients: [],
["BASE"]: 'fries'
}
}
My attempt to archive it looks like this so far:
export type DishActionType =
| { type: 'REMOVE_INGREDIENT'; ingredient: string }
| { type: 'ADD_INGREDIENT'; ingredient: string }
| { type: 'PICK_OPTION'; option: string; choice: string }
| { type: 'RESET' }
| { type: 'never' }
interface DishOptions {
[key: string]: string
}
// https://stackoverflow.com/a/45261035/618099
type DishOrder = DishOptions & {
id: string
withoutIngredients: string[]
}
type DishOrderState = DishOrder & {
initialState: DishOrder
}
function dishOrderReducer(state :DishOrderState, action :DishActionType) :DishOrderState {
switch (action.type) {
case 'REMOVE_INGREDIENT':
return {
...state,
withoutIngredients: [...state.withoutIngredients.push(action.ingredient).sort()],
}
case 'ADD_INGREDIENT':
return {
...state,
withoutIngredients: [...state.withoutIngredients].filter(
(ingredient) => ingredient != action.ingredient
),
}
case 'PICK_OPTION':
return {
...state,
[action.option]: action.choice
}]
case 'RESET':
return {
...state.initialState,
initialState: {...state.initialState}
}
default:
throw new Error(`No action case for this action type: ${action.type}`)
}
}
But vscode screams at me with
(property) withoutIngredients: string[]
Type '{ withoutIngredients: any[]; id: string; initialState: DishOrder; }' is not assignable to type 'DishOrderState'.
Type '{ withoutIngredients: any[]; id: string; initialState: DishOrder; }' is not assignable to type 'DishOptions'.
Property 'withoutIngredients' is incompatible with index signature.
Type 'any[]' is not assignable to type 'string'.
Hovering over the DishOrderState
shows this:
type DishOrderState = DishOptions & {
id: string;
withoutIngredients: string[];
} & {
initialState: DishOrder;
}