What is the best approach to replace null values with undefined specifically in object properties that cannot be assigned to?

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.

Answer №1

To utilize this method and replace all object values, simply spread it and apply removeNull(value) using the lodash library.

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

This can also be achieved without relying on lodash.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function does not throw a compiler error when a parameter is missing

Currently utilizing TSC Version 2.4.2 Please take note of the following interface: interface CallbackWithNameParameter { cb: (name: string) => void } This code snippet: const aCallback: CallbackWithNameParameter = { cb: () => {} }; Manages t ...

Learning Angular2: What is the mechanism behind the automatic incrementation of the ID variable in this particular section?

In This specific part of the Angular2 Tutorial there is a feature that allows users to add new items to an array. Somehow, when the item is added, the ID is automatically incremented but the exact process behind this automation remains a mystery. I am awa ...

Exploring the capabilities of utilizing Typescript decorators alongside the Parse SDK JS

In my Typescript project, I am utilizing the Parse SDK JS and have crafted a model class named Person that extends Parse.Object. This class is designed to store data on the server: import * as Parse from 'parse/node' class Person extends Parse. ...

"Utilize Typescript for defining the parameter type in this

defineProperties(Element.prototype, { querySelector: { value: querySelectorPatched, writable: true, enumerable: true, configurable: true, }, querySelectorAll: { value(this: HTMLBodyElement): NodeListOf< ...

Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public ...

Using Checkboxes in React with Material-UI

I am currently facing an issue with my 2 checkboxes. Whenever I select one, both of them get selected automatically. I want the user to be able to choose one, both, or none at all. It's puzzling why they are both getting selected simultaneously. Here ...

How to pass parameters between pages in Ionic 2 using navParams when the return nav button is clicked

Is there anyone familiar with how to return a simple value (or JSON) by clicking on the return button in Ionic 2's navigation bar? I understand that navParam can be used to send a value when pushing a page, but I am unsure how to implement the same fu ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

Manage numerous receiving bank accounts, allowing customers to transfer money to each specific account

Managing multiple receiving bank accounts and enabling customers to transfer money to specific accounts is a key requirement in my application. Can Plaid help me achieve this functionality? Could you provide guidance on how to implement this feature using ...

Angular2 encounters an error when processing a custom HTTP request

I offer two unique services Custom HTTP client service fetch(url):any{ this.storage.fetchData('auth-token').then((token) => { let headers = new Headers(); this.prepareHeaders(headers); return this.http.fetch(url+"?token="+toke ...

Switching between a single checkbox and a group of checkboxes: A step-by-step guide

My goal here is to design a group of checkboxes. The "Search everywhere" option is initially checked by default. If you check any other checkbox, the "Search everywhere" box automatically unchecks. You're allowed to check multiple checkboxes, but once ...

generate an object with the forEach method

When I receive data from a graphql query, my goal is to structure an object like the example below: const MY_DATA = [ { id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba', imageUrl: defaultUrl, name: 'Johann', } ...

Combining actions in a chain within an NgRx effect for Angular

After successfully working on an effect, I now face the challenge of chaining it with a service called in a subsequent action after updating the state in the initial action through a reducer. Here is the effect code: @Effect() uploadSpecChange$: Observab ...

JavaScript - Employing the .every function with an array containing objects

Is it possible to use the array.every method on multidimensional arrays? The structure of my array is as follows: tabs=[ {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: link}, {label: string, icon: icon, routerLink: ...

Comparison between typings and @types in the NPM scope

There are different approaches when it comes to handling TypeScript definitions. In some cases, the typings tool is used, as seen in projects like angular/angular2-seed. Alternatively, some projects use scoped NPM packages with the prefix @types, complete ...

Combining Different Types of Errors

Can TypeScript's type system be exploited to provide additional information from a repository to a service in case of errors? I have a service that needs a port for a repository (Interface that the Repository must implement), but since the service mu ...

Create an array filled with multiple arrays containing objects

To achieve the desired array of array of objects structure, I need to populate the data like this: let dataObj = [ [ { content: "test1"}, { content: "test2"}, { content: "test3"} ], [ ...

What is causing my React-Testing Library queries to not work at all?

In my current project, I am using Jest along with Testing-Library to create UI unit tests. One issue that I encountered was that the components were not rendering on the DOM. After some investigation, I found that the main culprit was a component called & ...

What is the process for declaring a module in order to perform named imports?

Currently, I am utilizing graphql-tag in my project. The structure of my files is as follows: ./operation.graphql Query User { ... } ./test.ts import { User } from './operation.graphql'; /// Module ''*.graphql'' has no ...

What is the best way to adjust the textfield's size proportionally to its parent accordion when the window is resized?

Inside an accordion, I placed a text field with specific widths and heights. However, when I resize the browser window, the accordion width changes proportionally to the window size while the text field width remains the same. This causes the text field to ...