Aessandro
Aessandro

Reputation: 5761

TypeScript type in React

I have the following and I am learning TypeScript on the go,

interface Props {
  contentHeight: number,
  dayRender(
    date: Date, 
    el: HTMLElement, 
    view: object
  ): void,
...

dayRender is a custom function of the plugin I am using: https://fullcalendar.io/docs/dayRender

and a component like so:

export class CalendarComponent extends Component<Props> {
  ...

  disableSaturday = ( slots: Array<{date: Date}> )  => {
    for(let i = 0; i < slots.length; i += 1) {
      if (getDay(slots[i].date) === Day.Sunday) {
        console.log(`it's saturday`)
      }
    }
  }

  render() {
    const { 
      contentHeight,
      dateClick,
      defaultView,
      displayEventTime,
      header,
      selectedAvailablity: { endDate, slots, startDate }, 
      selectedDate 
    } = this.props

    this.goToDate(selectedDate)
    return (
      <Fragment>
        <FullCalendar
          contentHeight={contentHeight}
          // dayRender={'sth on day render'}
          dateClick={dateClick}
          defaultView={defaultView}
          displayEventTime={displayEventTime}
          events={slots}
          dayRender={this.disableSaturday}
          firstDay={Day.Monday}
          header={header}
          now={selectedDate}
          plugins={[dayGridPlugin, interactionPlugin]}
          ref={this.calendarRef}
          validRange={{
            start: startDate,
            end: endDate,
          }}
        />
      </Fragment>
    ...

I have updated the Props interfact and updated the type of dayRender but and I am getting a type error:

enter image description here

Upvotes: 0

Views: 123

Answers (1)

Lu&#239;s
Lu&#239;s

Reputation: 2853

Your this.disableSaturday function is not compatible with what dayRender expects:

dayRender expects to receive a function with the following props { view: View; date: Date; allDay?: boolean | undefined; el: HTMLElement; }. But you gave it this.disableSaturday which wants { date: Date }[] as props. dayRender can't do anything with that as dayRender can only provide 1 { date: Date } object instead of an array of them.

To fix this you can simply do something like this:

dayRender(({ date }) => this.disableSaturday([date]))

The first date takes the date variable from dayRender. (destructuring).

The second part provides an array to disableSaturday with the 1 date variable in it.

Upvotes: 1

Related Questions