How set slotLabelFormat use constant

Viewed 25

I try to set slotLabelFormat options in react typescript project

In case slotLabelFormat={{ hour: "2-digit", minute: "2-digit", omitZeroMinute: false, meridiem: "short" }} typescript compiled and all work fine

But if I set constant like

const SLOT_LABEL_FORMAT = { hour: "2-digit", minute: "2-digit", omitZeroMinute: false, meridiem: "short" };

and try set

slotLabelFormat={SLOT_LABEL_FORMAT}

typescript don't compiled and have errors

Compiled with problems:

ERROR in src/Calendar/Calendar/components/CalendarView.tsx:119:9

TS2769: No overload matches this call.
  Overload 1 of 2, '(props: CalendarOptions | Readonly<CalendarOptions>): FullCalendar', gave the following error.
    Type '{ hour: string; minute: string; omitZeroMinute: boolean; meridiem: string; }' is not assignable to type 'FormatterInput | FormatterInput[] | undefined'.
      Type '{ hour: string; minute: string; omitZeroMinute: boolean; meridiem: string; }' is not assignable to type 'NativeFormatterOptions'.
        Types of property 'meridiem' are incompatible.
          Type 'string' is not assignable to type 'boolean | "short" | "lowercase" | "narrow" | undefined'.
  Overload 2 of 2, '(props: CalendarOptions, context: any): FullCalendar', gave the following error.
    Type '{ hour: string; minute: string; omitZeroMinute: boolean; meridiem: string; }' is not assignable to type 'FormatterInput | FormatterInput[] | undefined'.
    117 |         allDaySlot={false}
    118 |         locale="uk"
  > 119 |         slotLabelFormat={SLOT_LABEL_FORMAT}
        |         ^^^^^^^^^^^^^^^
    120 |         weekNumberCalculation="ISO" // Makes week calendar to start from monday
    121 |         slotMinWidth={72} // This property doesn't work (Fixed with styles)
    122 |         longPressDelay={50}
If try describe types for const will not expected result
1 Answers

When you pass the object literal as a prop, it knows to treat it as CalendarOptions and the object property "meridian" is narrowed to the literal type "short".

When you define the object beforehand, outside the context of the component prop, TypeScript infers the type of the object more broadly, and the type of "meridian" is instead string.

As you can see from the error:

Type 'string' is not assignable to type 'boolean | "short" | "lowercase" | "narrow" | undefined'.

an arbitrary string is not an acceptable value for this property.

You can instruct the compiler to infer the type of your object as narrowly as possible by using a const assertion, and then it should work as you want:

const SLOT_LABEL_FORMAT = { hour: "2-digit", minute: "2-digit", omitZeroMinute: false, meridiem: "short" } as const;

This causes each string property to be typed as its string literal value rather than string.

Related