How can we transfer or exclude all boolean properties from one class to another or a "type"?

Within my Nestjs application, there is an entity class structured like this:

@ObjectType()
export class Companies {
  @Field(() => Int)
  @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
  public id: number;

  @Field()
  @Column('enum', {
    name: 'status',
    enum: ['trial', 'live', 'disabled'],
    default: () => "'trial'"
  })
  public status: 'trial' | 'live' | 'disabled';

  @Field()
  @Column('tinyint', {
    name: 'status_inbound',
    width: 1,
  })
  public statusInbound: boolean;

I am interested in creating a new class that will exclusively inherit the boolean properties (status_inbound) from the existing company class.

CompaniesSettings {
  @Field()
  @Column('tinyint', {
    name: 'status_inbound',
    width: 1,
  })
  public statusInbound: boolean;
}

If additional boolean properties are later added to the Companies class, TypeScript should automatically acknowledge and permit these properties within the CompaniesSettings class. If selective inheritance of only boolean properties when defining a new class is not feasible, using types are also a viable solution.

type CompaniesSettings = Pick<Companies,'statusInbound'>

Answer №1

Retrieve all keys that are boolean values, then exclude the ones that are not:

type GetBoolKeys<T> = {
    [K in keyof T]: T[K] extends boolean ? K : never;
}[keyof T];

type OnlyBoolKeys<T> = Omit<T, Exclude<keyof T, GetBoolKeys<T>>>;

Alternatively, you could also extract all keys that are not booleans and eliminate them directly, but I find this method more logically clear.

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

What is the correct version compatibility matrix for Expo, NPM, Node, React Native, and TypeScript?

Currently, I am in the process of setting up React Native with TypeScript. Here are the steps I followed: npx react-native init MyApp --template react-native-template-typescript I made sure to install TypeScript as well: npm install -g typescript ' ...

Exploring ways to use TypeScript to export a Mongoose model?

There's a module I need to export in order to avoid the error "OverwriteModelError: Cannot overwrite Task model once compiled". I've tried various solutions but none seem to work. The problem lies in the last line (export default models...) impo ...

Developing a databound listview in Ionic: A step-by-step guide

In the world of programming, each platform has its own way of handling lists. For example, Android uses RecyclerView, WPF uses ListView, and in Ionic, we have ion-list. If you have a list of strings like this: Animals:string[] = ["Dog", "Cat", "Human", "C ...

"Enhance your Vue 3 projects with a dynamic library featuring universal components and full

Currently, I am in the process of developing a Vue 3 component library using Vue 3, Vite, and TypeScript. The unique aspect about this library is that it installs as a plugin and registers all components as global entities. Here is an overview of how this ...

Passing events from a parent component to dynamically created child components in Angular

UPDATE: I've decided to tackle this issue in a different way by retrieving dynamic child component values in the parent component's save() function, following the accepted answer. I am attempting to create a system where a parent component emits ...

Is there a way to signal an error within an Observable function that can handle multiple scenarios depending on the specific page being viewed in an Angular application?

Currently, I have a function called getElementList() which returns Observable<Element[]>. The goal is to handle different scenarios based on the user's current page - two cases for two specific pages and one error case. However, I am struggling ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

Snackbar and RTK Query update trigger the error message: "Warning: Cannot update during an existing state transition."

I've built a basic ToDos application that communicates with a NodeJS backend using RTK Query to fetch data, update state, and store cache. Everything is functioning properly as expected with the communication between the frontend and backend. Recently ...

Error: The checkbox was clicked, but an undefined property (includes) cannot be read

Link to live project preview on CodeSandbox Visit the product page with checkbox I have developed a code snippet that allows users to filter products by checking a box labeled "Show Consignment Products Only", displaying only those products with the term ...

Modify associated dropdown menus

I am trying to create an edit form that includes dependent select fields (such as country, state, city). The issue I am facing is that the edit only works when I reselect the first option (car brand) because I am using the event (change) with $event. How c ...

Issues with Angular 4 Rxjs subject subscription functionality

My application consists of a shared service named data.service.ts, which contains the following code: public pauseProjectTask$: Subject<any> = new Subject<any>(); pauseTaskProject(taskData, type){ this.pauseProjectTask$.next(taskData); ...

What is causing styled-components to include my attributes in the DOM?

In various parts of my code, there is a snippet like this: import React from 'react' import styled from 'styled-components' type PropsType = { direction?: 'horizontal' | 'vertical' flex?: number | string width ...

Exploring the potential of Socket.io and Angular with the seamless integration of

I have encountered an issue regarding the use of async pipe with Observables. Initially, I assumed that returning an Observable from my service on a socket.on event would suffice. However, it appears that my approach is incorrect. Can you guide me on the c ...

Function type guards in Typescript do not support type inference

When checking for null in alpha, I validate the result and use throw new Error if needed. However, even after doing so, the compiler still indicates a compilation error: const obj = { objMethod: function (): string | null { return 'always a str ...

How to Unsubscribe from an Angular 2 Subscription Automatically After a Timeout

I am looking for a way to disregard the response from my API in case it takes too long to fetch. Currently, I am using this.http.get(mysqlUrl).subscribe() to retrieve the response. However, I would like to terminate that subscription if it exceeds a dur ...

Navigating Through Angular Components

I have a layout with 3 components arranged like this: <app-header></app-header> <app-body></app-body> <app-footer></app-footer> However, I want to change the positioning of the footer and body as shown below: <app-he ...

Compiling an Angular project with an external library in AOT mode using angular-cli is causing issues and not compiling successfully

Embarking on a fresh new project, I utilized angular-cli 8.1.2 for the generation process. The goal is to establish a shared library that caters to multiple microservices (apps). This particular library should remain separate from the applications folder, ...

Changing the Class of an Element in a Different Component with Angular 2+

Currently in a project utilizing Angular 4, I have implemented two components: app.component and other.component Within app.component.html, there exists a div with the name attribute myClass. <div class="myClass"></div> In the other.componen ...

In search of assistance with resolving a React Typescript coding issue

I need help converting a non-TypeScript React component to use TypeScript. When attempting this conversion, I encountered the following error: Class 'Component' defines instance member function 'componentWillMount', but ext ...

Tips on transforming Angular 2/4 Reactive Forms custom validation Promise code into Observable design?

After a delay of 1500ms, this snippet for custom validation in reactive forms adds emailIsTaken: true to the errors object of the emailAddress formControl when the user inputs [email protected]. https://i.stack.imgur.com/4oZ6w.png takenEmailAddress( ...