typescript - 带有 type-graphql 的 NullObject 模式
问题描述
在处理继承和 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 | 空段。
但是当我执行以下操作时,@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>[]>
}
推荐阅读
- python-3.x - An issues with running "pip install Beautifulsoup" on cmd
- machine-learning - Pytorch VNet final softmax activation layer for segmentation. Different channel dimensions to labels. How do I get prediction output?
- python-3.x - How should I implement List annotation, which contains any type of objects?
- cmake - Linking mingw libs with cmake
- android-studio - Android studio create an update function
- r - Is there an R function to estimate cumulative incidence with aggregated survival data?
- powershell - Powershell_ISE 中的 New-IseSnippet 不保存变量?
- scala - 根据变量读取某些文件夹
- java - 使用流读取行并按块保存
- php - 如何使用 PHP 搜索包含多个单词的值的数据库?