How to replace the null values with undefined (in object properties) only in case of not assignable types?

912 views Asked by At
type GraphQLInput = {
  email: string;
  age?: null | number | undefined;
  height?: null | number | undefined;
}

type PrismaPerson = {
  email: string;
  age: number | undefined;
  height: null | number;
}

let input: GraphQLInput = {
  email: "[email protected]",
  height: null
}
let dbData: PrismaPerson = input

I need to assign input to dbData but there is incompatible type on age property.

let dbData: PrismaPerson
Type 'GraphQLInput' is not assignable to type 'PrismaPerson'.
  Types of property 'age' are incompatible.
    Type 'number | null | undefined' is not assignable to type 'number | undefined'.
      Type 'null' is not assignable to type 'number | undefined'.

I triet to clean all the null values with undefined but I don't know howto do change it only in case of not assignable types.

function cleanNullToUndefined(obj: any): any {
  if (obj === null) {
    return undefined;
  }
  if (typeof obj !== 'object') {
    return obj;
  }
  return Object.keys(obj).reduce((result, key) => ({
    ...result, 
    [key]: cleanNullToUndefined(obj[key])
  }), {});
}

let dbData: PrismaPerson = cleanNullToUndefined(input)
console.log(dbData)
// { email: '[email protected]', height: undefined }

My expected out is { email: '[email protected]', height: null } instead of { email: '[email protected]', height: undefined }

Any suggestions? Thanks.

1

There are 1 answers

0
Eunchurn Park On

Use this, but if you want to replace all object value, spread it and use removeNull(value) with lodash

function removeNull<T>(data: T | null | undefined) {
  if (isNull(data)) return undefined;
  return data
}

without lodash

function removeNull<T>(data: T | null | undefined) {
  if (typeof data === null) return undefined;
  return data
}