I'm encountering errors while trying to implement Set()
in my Grocery Shopping app using MobX with TypeScript. I have a simple setup with defined types in types.ts:
types.ts
export type Item = {
name: string;
instock: number;
price: number;
};
export type Buyer = {
cash: number;
items: Array<Pick<Item, 'name'> & { quantity: number }>;
};
export type IStore = {
items: Item[];
buyer: Buyer;
};
store.ts
import { observable, action, set, computed, makeObservable } from 'mobx';
import type { Item, IStore, Buyer } from './types';
export class Store implements IStore {
items: Item[] = [
{
name: "Egg",
instock: 30,
price: 4
},
{
name: "Apple",
instock: 24,
price: 20
},
{
name: "Banana",
instock: 60,
price: 8
}
]
buyer: Buyer = {
cash: 50,
items: [],
}
constructor() {
makeObservable(this, {
items: observable,
buyer: observable,
buyItem: action.bound,
});
}
buyItem(name: string, price: number, quantity: number) {
if (this.buyer.cash - price * quantity > 0) {
this.buyer.items.push({ name, quantity })
this.buyer.cash = this.buyer.cash - price * quantity
}
}
}
export const store = new Store();
I'm looking to use Set()
for the buyer
property in IStore. I want to change the type declaration in types.ts to utilize Set()
:
.
.
.
export type IStore = {
.
.
.
buyer: new Set<Buyer>();
};
Could someone shed light on this as the available docs lack a comprehensive example? How can I implement this change in store.ts
as well?
For a working example, check out this Stackblitz Reproduction.