Typescript – Check combinations of parameters are null

I wrote this function that construct an object based if some values are null or not.

protected temporalFilter({ range }: Filter): W {
    const temporalKey = ['created', 'bootedSince', 'firstComunication'];
    if (temporalKey.includes(range.key)) {
      if (range.from && !range.to) {
        return {
          [range.from as keyof T]: { gte: range.from }
        } as unknown as W;
      }
      else if (!range.from && range.to) {
        return {
          [range.to as keyof T]: { lte: range.to }
        } as unknown as W;
      }
      else if (range.from && range.to) {
        return {
          AND: [
            { [range.key as keyof T]: { lte: range.to } },
            { [range.key as keyof T]: { gte: range.from } }
          ]
        } as unknown as W;
      }
      else return {} as unknown as W;
    }
    else return null;
  }

But, there is a compact way to do that or some refactoring that can I do?

Answer

This is the most compact yet readable form I can think of:

temporalFilter({range}: Filter): W {
  if (['created', 'bootedSince', 'firstComunication'].includes(range.key)) {
    const f = range.from ? { [range.from]: {gte: range.from} } : undefined;
    const t = range.to ? { [range.to]: {lte: range.to} } : undefined;
    return ((f && t) ? { AND: [f, t] } : (f || t)) as unknown as W;
  } else {
    return null;
  }
}

I suggest you fix your typing; the usage of so many unknown in a single function suggests poor typing. Furthermore, this { [range.from]: {gte: range.from} } it is not wrong, but it is strange to have the same value as filtering condition and as key, perhaps you meant { [range.key]: {gte: range.from} }