diff --git a/src/types/filters.ts b/src/types/filters.ts index 8cc7eeb95..bb8b79f3c 100644 --- a/src/types/filters.ts +++ b/src/types/filters.ts @@ -17,36 +17,12 @@ export enum FilterTypes { ExcludableCheckboxGroup = 'XCheckbox', } -type SwitchFilter = { - type: FilterTypes.Switch; - /** Default value */ - value: boolean; -}; - -type TextFilter = { - type: FilterTypes.TextInput; - /** Default value */ - value: string; -}; - -type CheckboxFilter = { - type: FilterTypes.CheckboxGroup; - options: readonly FilterOption[]; - /** Default value */ - value: string[]; -}; -type PickerFilter = { - type: FilterTypes.Picker; - options: readonly FilterOption[]; - /** Default value */ - value: string; -}; - -type ExcludableCheckboxFilter = { - type: FilterTypes.ExcludableCheckboxGroup; - options: readonly FilterOption[]; - /** Default value */ - value: { +type FilterValueMap = { + [FilterTypes.TextInput]: string; + [FilterTypes.Picker]: string; + [FilterTypes.Switch]: boolean; + [FilterTypes.CheckboxGroup]: string[]; + [FilterTypes.ExcludableCheckboxGroup]: { /** Checkboxes marked as included */ include?: string[]; /** Checkboxes marked as excluded */ @@ -54,26 +30,30 @@ type ExcludableCheckboxFilter = { }; }; +type WithOptions = + | FilterTypes.Picker + | FilterTypes.CheckboxGroup + | FilterTypes.ExcludableCheckboxGroup; + +type OptionsOf = T extends WithOptions + ? { options: readonly FilterOption[] } + : object; + /** * key - filter pairs */ export type Filters = Record>; -/** Mapping of each FilterType to a Filter */ -type FilterFromType = { - [FilterTypes.CheckboxGroup]: CheckboxFilter; - [FilterTypes.ExcludableCheckboxGroup]: ExcludableCheckboxFilter; - [FilterTypes.Picker]: PickerFilter; - [FilterTypes.Switch]: SwitchFilter; - [FilterTypes.TextInput]: TextFilter; -}; - /** * Get type of a single filter type from the {@link FilterType} */ -export type Filter = { - label: string; -} & FilterFromType[Type]; +export type Filter = T extends FilterTypes + ? { + label: string; + type: T; + value: FilterValueMap[T]; + } & OptionsOf + : never; /** * Strip {@link FilterObject} object from 'label' and 'options' to get key - filter_value pairs @@ -94,18 +74,7 @@ export type FilterToValues< * Get value type for a {@link Filter} given it's FilterType * @see {@link FilterTypes} */ -export type ValueOfFilter = - T extends FilterTypes.CheckboxGroup - ? CheckboxFilter['value'] - : T extends FilterTypes.Picker - ? PickerFilter['value'] - : T extends FilterTypes.Switch - ? SwitchFilter['value'] - : T extends FilterTypes.TextInput - ? TextFilter['value'] - : T extends FilterTypes.ExcludableCheckboxGroup - ? ExcludableCheckboxFilter['value'] - : never; +export type ValueOfFilter = FilterValueMap[T]; /** Get {@link Filter}'s type */ export type FilterType = T extends {