'Build typescript function excluding undefined

I'm getting a ts error in assignment(TS2322) in a function that returns an object without undefined properties.

type Entries<T> = Exclude<{
  [P in keyof T]: [P, T[P]];
}[keyof T], undefined>[];

type ExcludeUndefined<T> = T extends object
  ? {
    [P in keyof T]-?: ExcludeUndefined<T[P]>;
  }
  : Exclude<T, undefined>;

export const getSerializable = <T>(obj: T): ExcludeUndefined<T> => {
  if (obj instanceof Array) {
    return obj
      .map((el) => getSerializable(el))
      .filter((el) => el !== undefined) as unknown as ExcludeUndefined<T>;
  }

  if (obj instanceof Object) {
    return (Object.entries(obj) as Entries<T>)
      .reduce((acc, [key, value]) => {
        if (value !== undefined) {
          // Type 'ExcludeUndefined<T[keyof T]>' is not assignable to type 'ExcludeUndefined<T>[keyof T]'.
          acc[key] = getSerializable(value);
        }

        return acc;
      }, {} as ExcludeUndefined<T>);
  }
  else {
    return obj as ExcludeUndefined<T>;
  }
};

I want to make this work without any assertion on acc[key] = getSerializable(value); line.

Is this possible? or Is there any other workaround to make such a function that doesn't mutate the input?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source