简体   繁体   中英

TypeScript dynamic property filtering mobx observable list

I have a calendar application I am building in React using Typescript. I am currently trying to store all my calendar events in a single observable object and select an array of events based on date

My events object looks like this

events = {
    '17-08-2020': [Array of events],
    '18-08-2020': [{}, {}, {}]
}

The idea behind this structure is that the date key will always be unique so a I can easily just push events into an array that this key identifies.

The problem occurs with typescript restricting me. When I access the store in my component I get this error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type .

When I try and use a computed property to get the element in my store I get getter must not have any formal parameters

Store

@observable events = {}

@computed 
get filteredEvents(key) {
    return this.events[key]
}

Just tell typescript that keys can be any string and not only predefined strings that you have on your events object.

events: {[key: string]: CalendarEventType[]} = {
  '17-08-2020': [{}, {}, {}],
  '18-08-2020': [{}, {}, {}]
}

For computed values with parameters you can follow the docs: Computeds with arguments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM