1
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: "some@email.com",
  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: 'some@email.com', height: undefined }

My expected out is { email: 'some@email.com', height: null } instead of { email: 'some@email.com', height: undefined }

Any suggestions? Thanks.

robert.little
  • 410
  • 3
  • 13

1 Answers1

0

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
}