Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extends/pick/omit all boolean props of class to another class or "type"

in my Nestjs app I have entity class which is looking like that:

@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 want to create class that will extend from this class only boolean properties (status_inbound).

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

So if there will be new boolean property added to Companies, typescript will recognize this and allow this property on CompaniesSettings class as well.
If extending (or picking) of only boolean props when declaring a new class is not possible, type is also usable.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type CompaniesSettings = Pick<Companies,'statusInbound'>

>Solution :

Get all keys that are booleans, then omit the ones that aren’t:

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>>>;

Another way would be to get all keys that aren’t booleans and exclude those directly but I think this is a little more logically understandable.

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading