Mikro-orm 中的 OptionalProps
OptionalProps in Mikro-orm
我正在研究如何定义额外的可选属性。
import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';
@Entity()
export abstract class BaseEntity {
[OptionalProps]?: 'createdAt';
@PrimaryKey()
id: number;
@Property()
createdAt: Date = new Date();
}
@Entity()
export class EntityA extends BaseEntity {
[OptionalProps]?: 'isAnotherProperty'; // This is the bit I cannot figure out
@Property()
isAnotherProperty: boolean = false;
}
上面的 TypeScript 抛出错误:
Property '[OptionalProps]' in type 'EntityA' is not assignable to the same property in base type 'BaseEntity'.
基本上我的 BaseEntity
和 EntityA
一样有可选属性。我可以从 BaseEntity
中删除 [OptionalProps]?:
并在 EntityA
中添加 [OptionalProps]?: 'createdAt' | 'isAnotherProperty';
,但是我的许多实体不需要 createdAt
之外的任何其他可选属性,所以我更喜欢不必在每个实体 class 中复制 [OptionalProps]?: 'createdAt';
如果我可以 'extend' 它在我需要的地方。
是否可以追加或覆盖 [OptionalProps]
?
可能最干净的方法是通过基本实体的类型参数:
import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';
@Entity()
export abstract class BaseEntity<O> {
[OptionalProps]?: O | 'createdAt';
@PrimaryKey()
id: number;
@Property()
createdAt: Date = new Date();
}
@Entity()
export class EntityA extends BaseEntity<'isAnotherProperty'> {
@Property()
isAnotherProperty: boolean = false;
}
我正在研究如何定义额外的可选属性。
import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';
@Entity()
export abstract class BaseEntity {
[OptionalProps]?: 'createdAt';
@PrimaryKey()
id: number;
@Property()
createdAt: Date = new Date();
}
@Entity()
export class EntityA extends BaseEntity {
[OptionalProps]?: 'isAnotherProperty'; // This is the bit I cannot figure out
@Property()
isAnotherProperty: boolean = false;
}
上面的 TypeScript 抛出错误:
Property '[OptionalProps]' in type 'EntityA' is not assignable to the same property in base type 'BaseEntity'.
基本上我的 BaseEntity
和 EntityA
一样有可选属性。我可以从 BaseEntity
中删除 [OptionalProps]?:
并在 EntityA
中添加 [OptionalProps]?: 'createdAt' | 'isAnotherProperty';
,但是我的许多实体不需要 createdAt
之外的任何其他可选属性,所以我更喜欢不必在每个实体 class 中复制 [OptionalProps]?: 'createdAt';
如果我可以 'extend' 它在我需要的地方。
是否可以追加或覆盖 [OptionalProps]
?
可能最干净的方法是通过基本实体的类型参数:
import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';
@Entity()
export abstract class BaseEntity<O> {
[OptionalProps]?: O | 'createdAt';
@PrimaryKey()
id: number;
@Property()
createdAt: Date = new Date();
}
@Entity()
export class EntityA extends BaseEntity<'isAnotherProperty'> {
@Property()
isAnotherProperty: boolean = false;
}