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

Time:03-14

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.

type CompaniesSettings = Pick<Companies,'statusInbound'>

CodePudding user response:

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

  • Related