New filters API with arrays

PHOTO EMBED

Thu Apr 08 2021 17:49:05 GMT+0000 (UTC)

Saved by [deleted user] #typescript

type FooFilter<T> = { type: 'Foo', foo: T }
type BarFilter<T> = { type: 'Bar', bar: T }
type Filter = FooFilter<unknown> | BarFilter<unknown>
type FilterShapeBase = [string, Filter][]

type ValueOf<F extends Filter> = 
F extends FooFilter<infer T> ? T
: F extends BarFilter<infer T> ? T
: never

type FilterValues<FilterShape extends FilterShapeBase> = FilterShape extends Array<infer U>
    ? U extends [infer K, infer F] 
        ? K extends string
            ? F extends Filter
                ? { [Key in K]: ValueOf<F> }
                : never
            : never
        : never
    : never

function f<FilterShape extends FilterShapeBase>(filters: FilterShape): FilterValues<FilterShape> {
    const tuples = filters.map(([key, filter]) => filter.type === 'Foo' ? [key, filter.foo] : [key, filter.bar])
    return Object.fromEntries(tuples)
}

/*
HOW TO CONFIGURE THE FILTER FilterShape:

type FilterShape = [
  ['foo_in', StringSearchFilter],
  ['bar_equals', EnumSelectOneFilter<MyEnum>]
]

const filters = [
  ['foo_in', { ... }],
  ['bar_equals', { ... }],
]
*/
content_copyCOPY

https://www.typescriptlang.org/play?target=6#code/C4TwDgpgBAYg9nGBLANsCAnAPAFQHxQC8UA3lKJAFxQDk8cNANFAGYLU5QC+AUBdACEAhhmRpMuAsTL9qNYRiZQARiI7c+4aGPQYisBDokBXAHYBrU3ADupggB8oCo9jOWbdzZFipdAZQALIUhhAGdoYgBtUOAMJFMAc2YXAF1IlJ4vaAA1IRRjCAB5FiwYKAgAD3RTABNQn3EMKSgeMsrquoNEXwl4lkwofCgAfkGeajaqiFr65x7sPoGh0ZxxqFMIADdMTP4G3Vz8iFDS+cDg6HbpzpdzkKFw5tug7yuZqABBDAwhECxFvQAVTwPCgYJGUEB5Sm70iAKgAGlmPCYCkWuCMRCEdCOvUYnFEqDMcTRpNcfsdsSqeDRmRIgiICAoPFESlqIcCsVSgReNTqdQNtsMES+VABVtKVTxUKRWL1hLhTwWGYAMbAJBwUysU6NO6XGE3M4vCBhCB4AAULHmoQmRouAEpbY0Occdf5jQQSLKVZqYuRjGAUMd9FbGqEAHQAW2C5vNkXMjOYod0KXtRAIycw4b2hFztHoNAh8cTrHm4bYcDR1GLICTZdUGFTsowEGAxgwWsKygAVhA1eWMHBIwBRUyxJDHc1twPHe08Xg8AD0ACoeAAJQoAdUGhSgAGFCgA5GAASQA4oCAErDwZrm+ngAyOGHl4pGD1lF2Wjfev0kSJkQ0BWAD68RKH446JH4EAiCqASpIwAE0A2wEQAAjsYeShEoo7GJG0FBmqhQbC4WAALIgLhkZ4BkGQ8D6ph+pmGD1FESEgWBzBkOGPHcCkiFgoBKHoZhKDYVxUA8eGfGIRky6LkAA