是否可以在 TypeORM 中使用 TypeScript 联合类型?

问题描述 投票:0回答:1

TypeORM 实体是否可以拥有由多种不同类型组成的字段?在纯 TypeScript 中,我会创建我想要的内容,如下所示:

type CustomType = Workout | Photo

interface Day {
    events: CustomType[]
}

我想要 TypeORM 中类似的东西(这个例子不起作用):

@Entity()
class Day {
    @OneToMany(() => CustomType, customType => customType.day)
    events: CustomType[]
}

我的问题是,TypeORM 中是否支持联合类型?

typescript typeorm
1个回答
0
投票

这很大程度上取决于您的联合类型的布局。

如果联合类型是像这样的字符串值的简单枚举

type CustomType = "Workout" | "Photo"

然后你可以使用 typeorm 轻松坚持下去。

如果它比你更复杂,则必须使用

@AfterLoad, @BeforeInsert, @BeforeUpdate
装饰器并编写自己的持久化策略。

示例

type Event =
| { kind: "Workout"; comment: string }
| { kind: "Photo"; timestamp: Date }

在您的实体中,您执行以下操作

@Entity("events")
class Events {
    //this is a fake definition so you pretend to access an Event value
    @Column({
        select: false,
        update: false,
        insert: false,
        nullable: true,
        type: "jsonb",
    })
    event!: Event

    //make the columns private as you prolly dont wont 
    //the table structure to become pulic
    @Column()
    private event_kind!: string
    @Column()
    private event_comment?: string
    @Column()
    private event_timestamp!: Date

    @AfterLoad()
    private readEvent() {
        switch (this.event_kind) {
            case "Workout":
                this.event = { 
                    kind: "Workout"; 
                    comment: this.event_comment 
                }
                break
            case "Photo":
                this.event = {
                    kind: "Photo",
                    timestamp: this.event_timestamp,
                }
                break

        }
    }
    @BeforeInsert()
    @BeforeUpdate()
    private writeEvent() {
        switch (this.event.kind) {
            case "Workout":
                this.event_kind = "Workout"
                this.event_comment = this.event.comment
                break
            case "Photo":
                this.event_kind = "Photo"
                this.event_timestamp = this.event.timestamp
                break
        }
    }

}

很高兴了解任何更简单的方法

© www.soinside.com 2019 - 2024. All rights reserved.