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: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb9884868eab8e868a8286c58883878186">[email protected]</a>",
height: null
}
let dbData: PrismaPerson = input
I am facing an issue where I need to assign the input
object to dbData
, but there is a type incompatibility with the 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 attempted to replace all null
values with undefined
, but I am unsure how to do it only in cases where types are not assignable.
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: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="41322e2c2401242c20282d6f222e2c">[email protected]</a>', height: undefined }
My desired output is
{ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8bf8e4e6ecbeee81efce9ae27fbdecdebcfe7adb0b9ede8edea">[email protected]</a>', height: null }
instead of { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05766a686045606864cbfdf1f5f0fff3fea6310103651b01076046431437303e31337f32232b3724297f34383a">[email protected]</a>', height: undefined }
Any ideas or suggestions? Thank you.