Descriptive term that alters a characteristic of a category

I am experimenting with TypeScript (4.5.2) and trying to build a generic that can alter certain properties of a given type.

type StrictNumber = {
  doesNotChange: string,
  nullable: false,
  value: number,
};

type MakeNullable<T extends { nullable: false, value: unknown }> = {
  [Property in keyof T]: Property extends 'nullable'
    ? true
    : Property extends 'value'
      ? T[Property] | null
      : T[Property]
};

type NullableNumber = MakeNullable<StrictNumber>;

This is the resulting NullableNumber type:

type NullableNumber = {
  doesNotChange: string,
  nullable: true,
  value: number | null,
};

The current implementation of the MakeNullable generic works as intended, but it seems quite verbose and inelegant. As more properties need modification, it becomes even more cumbersome.

Answer №1

To determine the value type, you can utilize a conditional type:

type MakeNullable<T extends { nullable: false, value: unknown }> = T extends { value: infer V }
    ? { nullable: true, value: V | null } : never;

Playground


If you wish to preserve all additional properties, you can create an intersection with the original type, while omitting the modified properties:

type MakeNullable<T extends { nullable: false, value: unknown }> = T extends { value: infer V }
    ? Omit<T, 'nullable' | 'value'> & { nullable: true, value: V | null } : never;

Playground


Alternatively, for a simpler approach (following @captain-yossarian's suggestion):

type MakeNullable<T extends { nullable: false, value: unknown }> =
    Omit<T, 'nullable' | 'value'> & { nullable: true, value: T['value'] | null }

Playground

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

Safeguarding user data across all components is facilitated by Angular 2

My Angular2 app uses OAuth2 with password grant type for authentication. I currently store the session token on sessionStorage, but I need to securely store additional data such as user roles. While I am aware that sessionStorage or localStorage can be ea ...

The element fa-icon is unrecognized within the Reusable Module

Can anyone help me understand why I am encountering this issue with a reusable Module (or what mistake I have made)? ERROR Error: Uncaught (in promise): Error: Template parse errors: 'fa-icon' is not a known element Just to clarify: fa-icon ...

Is it possible to determine the time format preference of the user's device in Angular? For example, whether they use a 24-hour system or a 12-hour system with AM

In Angular, is there a way to determine whether the user's time format is set to 24-hour or 12-hour system? Any help would be greatly appreciated. Thanks! ...

Developing a custom React Native function for applying 'Title Case' to text

I've been trying to create a function that automatically converts input from users into Title Case. The code I have written seems correct to me, but it's not producing the desired output. It's failing to capitalize the first letter of each w ...

combine string inputs when ng-click is triggered

Is there a way to pass a concatenated string using ng-click to MyFunction(param: string)? I have tried but so far, no luck: <input id="MeasurementValue_{{sample.Number}}_{{$index}}" ng-click="Vm.MyFunction('MeasurementValue_{{sample.Number ...

What is the best way to configure React children to only allow for a single string input

When using this component: <Component>example string</Component> How can I avoid the Typescript error related to type children: "example string" causing an issue? The 'children' prop of this JSX tag expects type '&qu ...

The AppModule has imported an unexpected value of '[object Object]', causing errors

How can I properly import the Pipe Module into my Angular app? import { NgModule } from '@angular/core'; import { PipeTransform, Pipe } from '@angular/core'; @Pipe({ name: 'values', pure: false }) export class CustomPipe im ...

Open a new browser tab with Angular using [href]

I am encountering an error where I am trying to open an href link in a new tab window. The error message says "Attribute is allowed only when 'href' is present." Is there a more efficient solution to achieve this using Angular? <t ...

Issue encountered: The differ cannot recognize the provided object '[object Object]', which is of type 'object'. NgFor is limited to binding Iterables only

I have been following a tutorial on Ionic created by Paul Halliday, focusing on a shopping list project that utilizes Firebase and Angular. However, I am encountering an error every time I try to run the application: Error: Uncaught (in promise): Error: ...

Unlocking the power of JSONB column filtering in KNEX with Typescript/Javascript: A comprehensive guide

Could someone please assist me with this query issue? I have a table with a jsonb column that stores stringified data in the following format: entry: { 1: "data1", 2: "data2" } I am trying to retrieve entries where the key is 1 ...

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

React Component Fails to Refresh After Redux Modifications

I've recently started learning about React and Redux, and I've been trying to solve a particular issue for the past few days. The problem I'm facing is that my React component doesn't re-render when Redux updates. Despite seeing the st ...

Methods for maintaining accuracy when updating a user's follower count using Node.js with MongoDB

In my latest project, I am developing a social API system that allows users to follow and unfollow each other. The user model I currently have set up looks like this: sourceId: { type: Schema.Types.ObjectId, ref: "user", required: t ...

Utilize data binding in Typescript to easily link variables between a service and controller for seamless utilization

Is there a way to overcome the issue of value assignment not binding data in this scenario? For example, using this.arrayVal = someService.arrayVal does not work as intended. The objective is to simplify the assignment in both HTML and controller by using ...

Secure your Vue Js application with authentication while maintaining a consistent URL for both the home and login components

Is it possible to implement authentication in a way that keeps the URL the same in the browser, similar to how Facebook does it? When a user is authenticated, they see the home page, and if not, they see the login page. However, the URL remains unchanged ...

Collaborating on projects using TypeScript, Node.js, and Angular

Currently, I am in the process of setting up a project that requires an angular client with a minimal node server on the backend using typescript. Ideally, I envision a folder structure as follows: / /dist : Angular client (production) files /server: Nod ...

How can I dynamically change and load a configuration file based on the URL parameter using Angular?

My query involves modifying the config file on pageload based on a URL parameter. I currently have implemented the following: config-loader.service.ts @Injectable() export class ConfigLoaderService { constructor(private injector: Injector, private ht ...

Running a Playwright test without relying on the command line

Is it possible to automate running a playwright test without having to manually input npx playwright test in the command line every time? I am looking for a way to initiate a playwright file from another file and have it execute without the need for acce ...

Error in TypeScript: Unable to assign type 'string' to type 'number | ""'

I am new to TypeScript and struggling to comprehend the error message below. Type '{ order: string; }[]' is not compatible with type 'TestType[]'. Type '{ order: string; }' is not assignable to type 'TestType'. ...

Setting up TypeScript and SCSS as the default languages for scripting and styling Vue components in Vite: A comprehensive guide

I recently developed a project utilizing Vue 2.8 and Vite. In order to incorporate TypeScript and SCSS, I found myself manually specifying them in each component: <script lang="ts"> <style scoped lang="scss"> Since the pr ...