[英]NullObject pattern with type-graphql
在处理 inheritance 和 NullObject 模式时,我有一个 typescript 问题。
考虑以下:
@ObjectType({ implements: Segment })
export class NullSegment extends Segment {
public static readonly NAME = 'Other'
@Field(() => Trait)
@ManyToOne(() => Trait)
trait: Trait
static build(input: NullSegmentInput): NullSegment {
const out = new this()
out.name = this.NAME
out.trait = input.trait
return out
}
}
export type NullableSegment<T extends Segment> = T | NullSegment
Segment还有很多其他的实现。
在其他地方我们有:
@ObjectType({ implements: Trait })
export class HealthScoreTrait extends Trait {
@Field(() => [NullableSegment<HealthscoreSegment>], { nullable: true })
@OneToMany(() => Segment, (segment) => segment.trait, {
onDelete: 'CASCADE',
cascade: true,
nullable: true
})
healthscoreSegments: NullableSegment<HealthscoreSegment>[]
}
当这解析为图表时,我希望可用的类型是 HealthScoreSegment | 空段。
但是当我执行以下操作时,@Field() 出现类型错误
有人知道这里的可行模式吗? 我需要为每个 Segment 制作 UnionTypes 对联吗? 这似乎真的不干
我不确定这是否是最佳答案......但这有效:
const NullableHealthscoreSegment = createUnionType({
name: "NullableHealthscoreSegment", // the name of the GraphQL union
types: () => [HealthscoreSegment, NullSegment] as const, // function that returns tuple of object types classes
});
@ObjectType({ implements: Trait })
@ChildEntity()
export class HealthScoreTrait extends Trait {
@Field(() => [NullableHealthscoreSegment], { nullable: true })
@OneToMany(() => Segment, (segment) => segment.trait, {
onDelete: 'CASCADE',
cascade: true,
nullable: true,
lazy: true,
})
healthscoreSegments: Lazy<NullableSegment<HealthscoreSegment>[]>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.