Mikro-orm 中的可选道具

2024-01-06

我正在尝试弄清楚如何定义其他可选属性。

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。我可以删除[OptionalProps]?: from BaseEntity并有[OptionalProps]?: 'createdAt' | 'isAnotherProperty'; in EntityA,但我的许多实体不需要任何额外的可选属性createdAt所以我不想重复[OptionalProps]?: 'createdAt';在每个实体类中,如果我可以在需要的地方“扩展”它。

是否可以追加或覆盖[OptionalProps]?


也许最干净的方法是通过基本实体上的类型参数:

import { Entity, PrimaryKey, Property, OptionalProps } from '@mikro-orm/core';

@Entity()
export abstract class BaseEntity<Optional = never> {

  [OptionalProps]?: Optional | 'createdAt';

  @PrimaryKey()
  id: number;

  @Property()
  createdAt: Date = new Date();

}

@Entity()
export class EntityA extends BaseEntity<'isAnotherProperty'> {

  @Property()
  isAnotherProperty: boolean = false;

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mikro-orm 中的可选道具 的相关文章

随机推荐