Replace null values with the undefined type in Typescript

Here is a scenario to consider:

The situation at hand entails having the following:

type A = {
   a: number | undefined
   b: string
}

// The desired outcome is for a helper type that transforms it into

type B = {
   a: number| null
   b: string
}

type A = {
   a: number | null
   b: string
}

// And here, we want a helper type that converts it back to its original form

type B = {
   a: number| undefined
   b: string
}

Is there a method to achieve this conversion? Attempts have been made to search online with limited success in finding relevant resources. It is crucial not to introduce null, but rather replace undefined with null. Additionally, is there another helper type capable of reverting this transformation?

Answer №1

If you want to iterate through all the properties and replace any occurrences of undefined with null, you can use a mapped type along with a conditional type. Additionally, you will need to eliminate optionality from the properties since optional properties are essentially a union with undefined.

type ReplaceUndefinedWithNull<T> = T extends undefined? null : T;
type ToNullProps<T> = {
  [P in keyof T]-?: ReplaceUndefinedWithNull<T[P]>
}

To reverse the types and replace any instances of null with undefined, you can create a similar set of types:

type ReplaceNullWithUndefined<T> = T extends null? undefined: T;
type ToUndefinedProps<T> = {
  [P in keyof T]: ReplaceNullWithUndefined<T[P]>
}

Playground Link

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

JavaScript Definition File for TypeScript

Within my repertoire is a Js File, comprised of a leaflet plugin, Js: L.BingLayer = L.TileLayer.extend({ options: { subdomains: [0, 1, 2, 3], type: 'Aerial', attribution: 'Bing', culture: '' }, initialize ...

Can a map key value be converted into a param object?

I have a map containing key-value pairs as shown below: for (let controller of this.attributiFormArray.controls) { attributiAttivitaMap.set(controller.get('id').value, { value: controller.get('valoreDefault').value, mandatory ...

Issues with TypeScript: Difficulty locating names in HTML templates

I recently upgraded my Angular 7 code to Angular 9 by following the steps outlined in the Angular Upgrade guide. However, upon completion of the migration process, I started encountering numerous "Cannot find name" errors within the HTML templates of my co ...

Utilize an array of observables with the zip and read function

I'm struggling with putting an array of observables into Observable.zip. I need to create a function that reads values from this dynamically sized array, but I'm not sure how to go about it. Does anyone have any suggestions? import {Observable} ...

Trigger a JavaScript function from a Python Temporal workflow

Presented is my Temporal workflow’s Python implementation: @workflow.defn class YourSchedulesWorkflow: @workflow.run async def run(self, name: str) -> str: //call javascript activity I have pre-existing JavaScript code that I wish to incorporate ...

Extract data from a string and assign it to a variable representing an

I have a custom function that parses a string and converts numbers and boolean values to their appropriate JavaScript primitives. This function is specifically designed for working with query parameters: const parseQueryParams = (searchString: string) => ...

The retrieval of cookies from the Response object is not possible with Typescript

While working on my google chrome extension, I implemented a post call that looks like this: public someapiCall(username: string, password: string) { var url = 'http://test.someTestServer.com/api/user/someApiCall'; let headers = new Hea ...

Angular 5 ngrx Effect is showing an error regarding the absence of an exported member called 'ofType'

Attempting to incorporate Effects into my ngrx state manager has been a challenge. I am currently utilizing Angular v5.2.1, ngrx v4.1.1, and rxjs v5.5.6. I experimented with the "older" approach, for instance: @Effect() login$: Observable<Action> = ...

Using setTimeout() and clearTimeout() alongside Promises in TypeScript with strict mode and all annotations included

Many examples of timer implementations using Promises in JavaScript seem overly complex to me. I believe a simpler approach could be taken. However, I am looking for a solution specifically tailored for TypeScript with the "strict": true setting and all ne ...

Combine all Typescript files into one JavaScript file without any extra steps

I'm fairly new to Typescript and I'm excited to use it for an upcoming JavaScript project. The modularity features that Typescript provides will make maintaining and developing the project much easier. I've organized each class in its own ts ...

Data retrieved from API not displaying in Angular Material table

I've hit a roadblock trying to understand why my mat-table isn't displaying the data for me. I'm working with Angular 15 and using Angular Material 15. Below is my HTML component code: <mat-divider></mat-divider> <table mat-t ...

What is the best way to transform private variables in ReactJS into TypeScript?

During my conversion of ReactJS code to TypeScript, I encountered a scenario where private variables were being declared in the React code. However, when I converted the .jsx file to .tsx, I started receiving errors like: Property '_element' d ...

What are the benefits of maintaining a property as non-observable instead of observable in knockout.js?

In my TypeScript project utilizing Knockout.js, I have a class with several properties. One of these properties is 'description', which is not directly tied to the DOM but needs to be used in popups triggered by certain mouse events (such as butt ...

An interface designed for enums containing nested types

My task involves creating an interface for the state using an enum as a key and object as a value. How can I designate the enum as the key type? export enum Language { CS, EN } const [userInput, setUserInput] = useState<IUserInput>({ [Lan ...

Applying specific data types to object properties for precise value identification in Typescript

I've been working on creating a dynamic settings menu in TypeScript using the following data: const userSettings = { testToggle: { title: "Toggle me", type: "toggle", value: false, }, testDropdow ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

How to properly display an Angular Template expression in an Angular HTML Component Template without any issues?

When writing documentation within an Angular App, is there a way to prevent code from executing and instead display it as regular text? {{ date | date :'short'}} Many sources suggest using a span element to achieve this: <span class="pun"&g ...

Is there a way to conceal an element within a component based on the current component being used with the router?

I have managed to hide an entire component, but I am unsure of how to show or hide specific elements within a component. export class AppComponent { headerFooterVisible: boolean; constructor(private router: Router) { router.events.subscribe(e =&g ...

The element is implicitly assigned an 'any' type due to the fact that an expression of type 'any' cannot be used to index types in nodejs and solidity

I am in need of setting networks in my contract using NodeJS and TypeScript. Below is the code I have written: let networkId: any = await global.web3.eth.net.getId(); let tetherData = await Tether.networks[networkId]; Unfortunately, I encountered ...

Show the login form and accompanying controls in the center of the screen with Angular 6

Currently, I am working on developing a Reactive form using Angular 6. In my TypeScript file, I have successfully obtained the form instance along with form controls. The next step involves iterating through these form controls and displaying the user inpu ...