如何 extends/pick/omit class 的所有布尔属性到另一个 class 或 "type"
How to extends/pick/omit all boolean props of class to another class or "type"
在我的 Nestjs 应用程序中,我有实体 class,它看起来像这样:
@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;
我想创建 class,它将仅从此 class 扩展布尔属性 (status_inbound)。
CompaniesSettings {
@Field()
@Column('tinyint', {
name: 'status_inbound',
width: 1,
})
public statusInbound: boolean;
}
因此,如果将新的布尔值 属性 添加到 Companies,typescript 将识别这一点并允许在 CompaniesSettings class 上使用此 属性。
如果在声明新 class 时仅扩展(或选择)布尔道具是不可能的,那么 type 也是可用的。
type CompaniesSettings = Pick<Companies,'statusInbound'>
获取所有布尔值的键,然后忽略不是布尔值的键:
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>>>;
另一种方法是获取所有 不是 布尔值的键并直接排除它们,但我认为这在逻辑上更容易理解。
在我的 Nestjs 应用程序中,我有实体 class,它看起来像这样:
@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;
我想创建 class,它将仅从此 class 扩展布尔属性 (status_inbound)。
CompaniesSettings {
@Field()
@Column('tinyint', {
name: 'status_inbound',
width: 1,
})
public statusInbound: boolean;
}
因此,如果将新的布尔值 属性 添加到 Companies,typescript 将识别这一点并允许在 CompaniesSettings class 上使用此 属性。 如果在声明新 class 时仅扩展(或选择)布尔道具是不可能的,那么 type 也是可用的。
type CompaniesSettings = Pick<Companies,'statusInbound'>
获取所有布尔值的键,然后忽略不是布尔值的键:
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>>>;
另一种方法是获取所有 不是 布尔值的键并直接排除它们,但我认为这在逻辑上更容易理解。