【发布时间】:2020-11-07 18:32:08
【问题描述】:
在处理继承和 NullObject 模式时,我有一个打字稿问题。
考虑以下几点:
@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 | NullSegment。
但是当我执行以下操作时,@Field() 出现类型错误
有人知道这里可行的模式吗?我需要为每个 Segment 制作 UnionTypes 对联吗?这似乎真的不干
【问题讨论】:
-
您是否尝试过使用泛型类型(类)? typegraphql.com/docs/generic-types.html
-
不,我确实知道这种模式。我会试一试——这看起来像是要走的路
标签: typescript graphql typegraphql